列表<列表<字符串>>

本文关键字:列表 字符串 | 更新日期: 2023-09-27 18:01:57

我有一个对象列表,每个对象都有一个字符串的子列表。我正在尝试在子列表中获得唯一字符串的计数。

示例对象:

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"}}
    };
预期输出:

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

谢谢

列表<列表<字符串>>

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