Sum nested values with Linq

后端 未结 1 550
面向向阳花
面向向阳花 2021-02-07 18:00

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:45

    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)
提交回复
热议问题