Lets say I have a flat list of objects, each of which has a person’s name, and a single Role they’re in, like so:
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" },
};
Now, is there a direct way to get this into a Dictionary<string, List<string>> based on Name and Role (obviously). I did it in two steps, like below, but I have to think there’s a more direct way.
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));
Thanks!
1 Answer