LINQ sum collection of items to return object with results (multiple columns)

item totals = new item 
              { 
                 net = items.Sum(i => i.net),
                 total = items.Sum(i => i.total)  
              };

But keep in mind that this query will enumerate a list two times, so for a large list this would not so efficient as old good single foreach loop.


var item = new item();
item.net = items .Sum(x=>x.net);
item.total = items.Sum(x=>x.total);

It looks like you really want:

var result = new {
    NetGrand = items.Sum(t => t.net),
    TotalGrand = items.Sum(t => t.total)
};

On the other hand, I'd probably just separate those into two different local variables:

var netGrand = items.Sum(t => t.net);
var totalGrand = items.Sum(t => t.total);

Of course this iterates over the list twice, but in most cases I'd expect that not to be noticeable.


If you don't care about iterating the list twice,

var i = new item
    { 
        net = items.Sum(it => it.net), 
        total = items.Sum(it => it.total) 
    };

If you do care about iterating the list twice (as you might be if you were doing this for an IEnumerable of unknown origin),

var i = items.Aggregate(new item(), 
    (accumulator, it) => 
        new item 
        {
            net = accumulator.net + it.net, 
            total = accumulator.total + it.total 
        } 
);

Tags:

C#

Linq