简体   繁体   中英

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 ?

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);

使用Sum和GroupBy然后打印结果。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM