1

The relationship between them is one order to many journals. Now I want to get the sum of all pending orders (or records that are flagged as false under IsDelivered in Order entity).

So far, I have this query but can't seem to get working when I add .Sum()

Orders .Where(o => o.IsDelivered == false) .Select(o => new { pendingOrders = o.Journals.Sum(j => j.TotalAmount) })

So far this results to:

In a nutshell, how can I get the sum of them? If query needs to be altered or should be a new one. It is welcome. Any help would be much appreciated. Thanks!

2 Answers 2

4

You can do it in several ways:

  • You could add Sum(n => n.pendingOrders) to the end of your query to add up the values, or
  • You could use SelectMany before Select, and use Sum instead of Select.

Either of the two approaches is going to work.

Sign up to request clarification or add additional context in comments.

Comments

3

In this case, it is easiest to use SelectMany (MSDN) to flatten your collections, then use Sum:

Orders.Where(o => !o.IsDelivered).SelectMany(o => o.Journals).Sum(j => j.TotalAmount);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.