Sum nested values with Linq

后端 未结 1 1949
野趣味
野趣味 2021-02-07 18:03

Simple problem: I have Users that can have many Orders that can have many Products. What does the Linq (lambda) query look like to get a User\'s grand total of all Product.Pric

相关标签:
1条回答
  • 2021-02-07 18:20
    int total = (from user in users
                 from order in user.Orders
                 from product in order.Products
                 select (int?)product.Price).Sum() ?? 0;
    

    would be my offering; there is an annoying glitch that the SUM in SQL over 0 rows is NULL, not 0 - the above works around that.

    or as lambdas (from comments):

    int total = users.SelectMany(user => user.Orders)
                     .SelectMany(order => order.Products)
                     .Sum(product => (int?)product.Price) ?? 0;
    
    0 讨论(0)
提交回复
热议问题