Reputation: 13
I have a list of objects each with a child list of string. I am trying to get a count on unique strings in the child lists.
Example objects:
private class ForumUser
{
public List<string> RegisteredForums { get; set; }
}
Pupulating the example
List<ForumUser> forumUsers = new List<ForumUser>
{
new ForumUser {RegisteredForums = {"Forum1", "Forum2"}},
new ForumUser {RegisteredForums = {"Forum1", "Forum2", "Forum3"}},
new ForumUser {RegisteredForums = {"Forum1", "Forum2", "Forum3", "Forum4"}},
new ForumUser {RegisteredForums = {"Forum1", "Forum2", "Forum3", "Forum4", "Forum5"}}
};
Expected output:
Dictionary<'distinct forum name', 'count of forum'> result
Dictionary<string, int> result = forumUsers.GroupBy(<your cleverness here>
Forum1, 4
Forum2, 4
Forum3, 3
Forum4, 2
Forum5, 1
thank you
Upvotes: 1
Views: 2305
Reputation: 18474
forumUsers.SelectMany (x=> x.RegisteredForums ).GroupBy (x => x).ToDictionary (x =>x.Key,x=>x.Count())
Upvotes: 6