假设我有一个平面的对象列表,每个对象都有一个人的名字,以及他们所在的单个角色,如下所示:
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));
谢谢!
答案 0 :(得分:5)
Dictionary<string, List<string>> dictionary = people.GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.Select(p => p.Role).ToList());
未经测试,但我认为这应该有用......
编辑现在进行测试,确实有效。
答案 1 :(得分:3)
这应该这样做:
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);
答案 2 :(得分:2)
var dict = People.ToLookup(p=>p.Name, p=>p.Role)
.ToDictionary(it=>it.Key, it=>it.ToList());
答案 3 :(得分:1)
var result = People.GroupBy(a => a.Name).ToDictionary(a => a.First().Name, b => b.Select(c => c.Role).ToList());
答案 4 :(得分:1)
People
.GroupBy( p => p.Name )
.ToDictionary( p => p.Key, p => p.Select(pr => pr.Role).ToList() )