是否有更好的LINQ Query可以做到这一点

本文关键字:这一点 Query 更好 LINQ 是否 | 更新日期: 2023-09-27 18:01:01

假设我有一个对象的平面列表,每个对象都有一个人的名字,以及他们所处的单个角色,如下所示:

        var People = new[] { 
            new PersonRole(){ Name = "Adam", Role = "R1" },
            new PersonRole(){ Name = "Adam", Role = "R2" },
            new PersonRole(){ Name = "Adam", Role = "R3" },
            new PersonRole(){ Name = "Bob", Role = "R1" },
        };

现在,有没有一种直接的方法可以将其转换为基于名称和角色的Dictionary<string, List<string>>(显然(。我分两步完成,如下所示,但我必须认为还有更直接的方法。

Dictionary<string, List<string>> resultLookup = 
   People.Select(p => p.Name).Distinct().ToDictionary(str => str, str => new List<string>());
People.ForEach(p => resultLookup[p.Name].Add(p.Role));

谢谢!

是否有更好的LINQ Query可以做到这一点

Dictionary<string, List<string>> dictionary = people.GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.Select(p => p.Role).ToList());

未经测试,但我认为这应该有效。。。

EDIT现在测试它,事实上它确实有效。

这应该做到:

var people = new[] { 
    new { Name = "Adam", Role = "R1" },
    new { Name = "Adam", Role = "R2" },
    new { Name = "Adam", Role = "R3" },
    new { Name = "Bob", Role = "R1" },
};
var r = from p in people
        group p by p.Name
        into g
        select new {
            Name = g.Key,
            Roles = g.Select(p => p.Role).ToList()
        };
var d = r.ToDictionary(k => k.Name, e => e.Roles);
var dict = People.ToLookup(p=>p.Name, p=>p.Role)
  .ToDictionary(it=>it.Key, it=>it.ToList());
 var result = People.GroupBy(a => a.Name).ToDictionary(a => a.First().Name, b => b.Select(c => c.Role).ToList());
People
.GroupBy( p => p.Name )
.ToDictionary( p => p.Key, p => p.Select(pr => pr.Role).ToList() )