列表上的Linq Count Group <list <string>&gt; </list <string>

时间:2011-07-11 10:45:40

标签: c# .net linq c#-4.0

我有一个对象列表,每个对象都有一个子字符串列表。我试图计算子列表中的唯一字符串。

示例对象:

private class ForumUser
{
    public List<string> RegisteredForums { get; set; }
}

举例说明

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"}}
    };

预期产出:

字典&lt;'独特论坛名称','论坛数'&gt;结果

Dictionary<string, int> result = forumUsers.GroupBy(&lt;your cleverness here&gt;
Forum1, 4
Forum2, 4
Forum3, 3
Forum4, 2
Forum5, 1

谢谢

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

forumUsers.SelectMany(f => f.RegisteredForums).GroupBy(s => s)