我有一个对象列表,每个对象都有一个子字符串列表。我试图计算子列表中的唯一字符串。
示例对象:
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(<your cleverness here>
Forum1, 4
Forum2, 4
Forum3, 3
Forum4, 2
Forum5, 1
谢谢
答案 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)