Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a SUM in Linq?

Tags:

c#

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?

like image 876
gurehbgui Avatar asked Apr 27 '13 10:04

gurehbgui


People also ask

How do you sum two columns in Linq?

Items select new { Sum(p. Total), Sum(p. Done)};

What is aggregate in Linq C#?

In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.


3 Answers

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) });
like image 186
dtb Avatar answered Oct 13 '22 15:10

dtb


Try it ,

 .GroupBy(x => x.id)
 .Select(n => n.Sum(m => m.count));
like image 23
zey Avatar answered Oct 13 '22 14:10

zey


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
like image 40
Branko Dimitrijevic Avatar answered Oct 13 '22 16:10

Branko Dimitrijevic