Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Here I have

System.Collections.Generic.KeyNotFoundException: 'The given key 'EmptyProjectionMember' was not present in the dictionary.'

var res = (from c in _context.Check
             join cp in _context.CheckProduct on c.Id equals cp.CheckId
             join p in _context.Product on cp.ProductId equals p.Id
             where c.Date.Date == date.Date
             select (cp.Quantity * Decimal.ToDouble(p.Price))).Sum();

But when I write this, the code is working:

var res = (from c in _context.Check
             join cp in _context.CheckProduct on c.Id equals cp.CheckId
             join p in _context.Product on cp.ProductId equals p.Id
             where c.Date.Date == date.Date
             select (cp.Quantity * Decimal.ToDouble(p.Price)));
double sum = 0;          
foreach(var el in res)
   sum += el;

Why Sum() is not working?

You need to pass parameter to Sum() the attribute you want to calculate. Something like this Sum(cp.Quantity * Decimal.ToDouble(p.Price))) – Long Luong Aug 23, 2020 at 9:52 Does this answer your question? How to force LINQ Sum() to return 0 while source collection is empty – Salik Rafiq Aug 23, 2020 at 14:40

Try the following:

res = (from c in _context.Check
           join cp in _context.CheckProduct on c.Id equals cp.CheckId
           join p in _context.Product on cp.ProductId equals p.Id
           where c.Date.Date == date.Date
           select (cp.Quantity * Decimal.ToDouble(p.Price)))
          .DefaultIfEmpty(0)
          .Sum();

Looks like there is nothing to select, so in that case, default to 0.

In the second case, you try to iterate an empty enumerable so it won't even go into the for each clause.

I was getting the same error when calling Any with an unsatisfied filter

public static bool IsBooking(this Address address)
    => address.ReferenceTypes.Any(referenceType 
        => referenceType == ReferenceType.Booking 
        && address.IsActive);

After first making sure that some elements exist, it is working - but it doesn't really make sense as now I'm calling Any twice

public static bool IsBooking(this Address address)
    => address.ReferenceTypes.Any()
        && address.ReferenceTypes.Any(referenceType
        => referenceType == ReferenceType.Booking
        && address.IsActive);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.