Multiple SUM using LINQ

后端 未结 5 2679
无人共我
无人共我 2021-02-20 18:14

I have a loop like the following, can I do the same using multiple SUM?

foreach (var detail in ArticleLedgerEntries.Where(pd => pd.LedgerEntryType == LedgerEn         


        
5条回答
  •  悲哀的现实
    2021-02-20 18:31

    You could also group by true - 1 (which is actually including any of the items and then have them counted or summered):

     var results = from x in ArticleLedgerEntries
                           group x by 1
                           into aggregatedTable
                           select new
                                      {
                                          SumOfWeight = aggregatedTable.Sum(y => y.weight),
                                          SumOfLength = aggregatedTable.Sum(y => y.Length),
                                          SumOfNrDistaff = aggregatedTable.Sum(y => y.NrDistaff)
                                      };
    

    As far as Running time, it is almost as good as the loop (with a constant addition).

提交回复
热议问题