Get sum of two columns in one LINQ query

后端 未结 9 1002
猫巷女王i
猫巷女王i 2020-12-01 09:04

let\'s say that I have a table called Items (ID int, Done int, Total int)

I can do it by two queries:

int total = m.Items.Sum(p=>p.Total)
int done         


        
9条回答
  •  感动是毒
    2020-12-01 09:32

    With a helper tuple class, either your own or—in .NET 4—the standard ones you can do this:

    var init = Tuple.Create(0, 0);
    
    var res = m.Items.Aggregate(init, (t,v) => Tuple.Create(t.Item1 + v.Total, t.Item2 + v.Done));
    

    And res.Item1 is the total of the Total column and res.Item2 of the Done column.

提交回复
热议问题