简体   繁体   中英

Linq Total of a Group

I have a List of Person and each person has an Color.Name

I need to basically get a simple object like :

 "Blue", 50
 "Green", 70

Etc

List<Person> people....;

people.GroupBy(p=>p.Color.name)    ?????

Use Select

List<Person> people....;

people.GroupBy(p=>p.Color.name)
      .Select(g => new { Color = g.Key, Count = g.Count() });

You can replace new { Color = g.Key, Count = g.Count() } with anything you like to get the desired output, like "\\"" + g.Key + "\\", " + g.Count() to get exactly the string listing you have in your question.

Having a GroupBy produces objects with a Key property and an Enumerable of the objects within each Group. The Key can either be a simple type like a string or a complex object (like a Person).

So the following, for each Group, it will get you the name (x.Key) and the Count of the objects within that group (color name).

people.GroupBy(p=>p.Color.name).Select(x=>new {Color = x.Key, Count= x.Count()});

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