locked
How to get sum of all parent and child elements in linq? RRS feed

  • Question

  • User-1564432484 posted

    I have records of parent elements which also have child elements. Parent as well as child has ExtendedListPrice field. I need to show sum of this field whether the data is of Parent or child. How to achieve this? Shall I first get the total of all Parent elements and then add sum of all child elements?

    Sunday, October 7, 2018 1:46 PM

All replies

  • User1120430333 posted

    How to achieve this? Shall I first get the total of all Parent elements and then add sum of all child elements?

    That's how you do it. 1 parent value + add sum of all children using the Sum() aggregate. 

    Sunday, October 7, 2018 3:59 PM
  • User1520731567 posted

    Hi rameezshaikh56,

    hall I first get the total of all Parent elements and then add sum of all child elements?

    I think so,I suggest you could use SelectMany() and Sum() to get all child elements' sum firstly, then get all parent elements' sum by the same way.

    For example:

      var  total = (from user in db.authors
                             from books in user.book
                             select (int?)books.Id).Sum() ?? 0;

    Note: the SUM in SQL over 0 rows is NULL, not 0

    or as lambdas (from comments):

    var total = db.authors.SelectMany(user => user.book).Sum(books=> (int?)books.Id) ?? 0;

    I find the similar question from this link,you could refer to it:

    https://stackoverflow.com/questions/5893445/sum-nested-values-with-linq

    Best Regards.

    Yuki Tao

    Monday, October 8, 2018 9:44 AM