gurehbgui
gurehbgui

Reputation: 14674

how to get a SUM in Linq?

I need to do the following, I have a List with a class which contains 2 integer id and count

Now I want to do the following linq query:

get the sum of the count for each id

but there can be items with the same id, so it should be summerized e.g.:

id=1, count=12
id=2, count=1
id=1, count=2

sould be:

id=1 -> sum 14
id=2 -> sum 1

how to do this?

Upvotes: 16

Views: 45049

Answers (3)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

The following program...

struct Item {
    public int Id;
    public int Count;
}

class Program {

    static void Main(string[] args) {

        var items = new [] {
            new Item { Id = 1, Count = 12 },
            new Item { Id = 2, Count = 1 },
            new Item { Id = 1, Count = 2 }
        };

        var results =
            from item in items
            group item by item.Id
            into g
            select new { Id = g.Key, Count = g.Sum(item => item.Count) };

        foreach (var result in results) {
            Console.Write(result.Id);
            Console.Write("\t");
            Console.WriteLine(result.Count);
        }

    }

}

...prints:

1       14
2       1

Upvotes: 3

zey
zey

Reputation: 6105

Try it ,

 .GroupBy(x => x.id)
 .Select(n => n.Sum(m => m.count));

Upvotes: 3

dtb
dtb

Reputation: 217253

Group the items by Id and then sum the Counts in each group:

var result = items.GroupBy(x => x.Id)
                  .Select(g => new { Id = g.Key, Sum = g.Sum(x => x.Count) });

Upvotes: 27

Related Questions