简体   繁体   中英

How can I generate a List<KeyValuePair<string, int>> consisting of groupings from another list?

I want to make a List<KeyValuePair<string, int>> with contains zip codes and the number of people living at each location.

The data is coming from another list, which is a List<Member> . The Member -class looks like this:

public class Member
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Zip { get; set; }
    // some more properties
}

This is the code I have so far:

List<KeyValuePair<string, int>> zipCount = new List<KeyValuePair<string, int>>();
foreach (Member member in members)
{
    zipCount.Add(new KeyValuePair<string, int>(member.Zip, 1));
}

Now, obvoiusly I am missing some linq code to group members by zip code.

What would such linq code look like? I have tried foreach (Member member in members.GroupBy(g => g.Zip)) , but that throws this error message:

InvalidCastException: Unable to cast object of type 'System.Linq.Grouping`2[System.String,SolutionName.Models.Member]' to type 'SolutionName.Models.Member'.

This should work:

var zipCount = members.GroupBy(m => m.Zip)
    .Select(g => new KeyValuePair<string, int>(g.Key, g.Count()))
    .ToList();

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