Get sum of two columns in one LINQ query

后端 未结 9 930
猫巷女王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.

    0 讨论(0)
  • 2020-12-01 09:38
    //Calculate the total in list field values
    //Use the header file: 
    
    Using System.Linq;
    int i = Total.Sum(G => G.First);
    
    //By using LINQ to calculate the total in a list field,
    
    var T = (from t in Total group t by Total into g select g.Sum(t => t.First)).ToList();
    
    //Here Total is a List and First is the one of the integer field in list(Total)
    
    0 讨论(0)
  • 2020-12-01 09:42

    To sum the table, group by a constant:

    from p in m.Items
    group p by 1 into g
    select new {
        SumTotal = g.Sum(x => x.Total),
        SumDone = g.Sum(x => x.Done)
    }
    
    0 讨论(0)
提交回复
热议问题