Search code examples
c#arraysjsonlinqprojection

Using LINQ to project a list to a key / count 2-dimensional array


Let's say I have a list of an object like this:

var users = new List<User>();
users.Add(new User() { FirstName = "Ek0nomik" });
users.Add(new User() { FirstName = "Ek0nomik" });
users.Add(new User() { FirstName = "Foobar" });

I am trying to get a 2-dimensional array that contains the name and the count of that name (for the purpose of returning it as JSON with use in Google Charts) from that list. This is what the array would contain:

["Ek0nomik", 2],
["Foobar", 1]

I was initially trying to use .Select to project a new object, but that projects for each object within the list so I don't think that method will get me there.


Solution

  • users.GroupBy(x => x.FirstName)
         .Select(x => new { Name = x.Key, Count = x.Count() })