Shahin
Shahin

Reputation: 12861

Linq to list query C#

There is a list of a class in my software with these properties :
Name -- Quantity
list may contains these data :
name1 -- 12
name1 -- 10
name2 -- 10
name2 -- 5
I need a output like this :
name1 -- 22
name2 -- 15
I can make this output with messy code (with for each and etc) but how can I provide this with LINQ query ?

Upvotes: 2

Views: 592

Answers (2)

Silas
Silas

Reputation: 1150

Use Sum and GroupBy and then print the results.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564831

You can use Enumerable.GroupBy and Enumerable.Sum.

It would look similar to:

var values = theCollection
                .GroupBy(item => item.Name)
                .Select(g => new { Name = g.Key, Total = g.Sum(i => i.Value) });

foreach(var value in values)
    Console.WriteLine("{0} - {1}", value.Name, value.Total);

Upvotes: 7

Related Questions