简体   繁体   中英

Linq Count Group on List<List<string>>

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(&lt;your cleverness here&gt;
Forum1, 4
Forum2, 4
Forum3, 3
Forum4, 2
Forum5, 1

thank you

forumUsers.SelectMany (x=> x.RegisteredForums ).GroupBy (x => x).ToDictionary (x =>x.Key,x=>x.Count())
forumUsers.SelectMany(f => f.RegisteredForums).GroupBy(s => s)

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