LINQ - Group By child property

时间:2018-04-07 17:37:40

标签: linq

我有一个用户列表,每个用户都有一个名为Tags的字符串数组属性。我想获得一个独特的标签列表和总计数,任何想法我在这里失踪了什么?我使用LinqPad编写测试查询,请参阅示例代码:

void Main()
{
    List<User> users = new List<User>(){
        new User {Id = 1, Tags = new string[]{"tag1", "tag2"}},
        new User {Id = 2, Tags = new string[]{"tag3", "tag7"}},
        new User {Id = 3, Tags = new string[]{"tag7", "tag8"}},
        new User {Id = 4, Tags = new string[]{"tag1", "tag4"}},
        new User {Id = 5 },
    };

    var uniqueTags = users.Where(m=>m.Tags != null).GroupBy(m=>m.Tags).Select(m=> new{TagName = m.Key, Count = m.Count()});
    uniqueTags.Dump();

    // RESULT should BE:
    // tag1 - Count(2)
    // tag2 - Count(1)
    // tag3 - Count(1)
    // tag4 - Count(1)
    // tag7 - Count(2)
    // tag8 - Count(1)
}

public class User{
    public int Id {get;set;}
    public string[] Tags {get;set;}
}

1 个答案:

答案 0 :(得分:1)

在分组之前,您可以展平为Players

IEnumerable<string>

LINQPad C#Expression版本:

var uniqueTags = users.SelectMany(u => u.Tags ?? new string[0])
                      .GroupBy(t => t)
                      .Select(g => new { TagName = g.Key, Count = g.Count() } );
相关问题