Get sum of two columns in one LINQ query

后端 未结 9 1003
猫巷女王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:31

    This has been answered already, but the other answers will still do multiple iterations over the collection (multiple calls to Sum) or create lots of intermediate objects/Tuples which may be fine, but if it isn't, then you can create an extension method (or multiple) that does it the old-fashioned way but fits well in a LINQ expression.

    Such an extension method would look like this:

    public static Tuple Sum(this IEnumerable collection, Func selector1, Func selector2)
    {
        int a = 0;
        int b = 0;
    
        foreach(var i in collection)
        {
            a += selector1(i);
            b += selector2(i);
        }
    
        return Tuple.Create(a, b);
    }
    

    And you can use it like this:

    public class Stuff
    {
        public int X;
        public int Y;
    }
    
    //...
    
    var stuffs = new List()
    {
        new Stuff { X = 1, Y = 10 }, 
        new Stuff { X = 1, Y = 10 }
    };
    
    var sums = stuffs.Sum(s => s.X, s => s.Y);
    

提交回复
热议问题