c# - Is there a better LINQ Query to do this? -
lets have flat list of objects, each of has person's name, , single role they're in, 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, there direct way dictionary<string, list<string>>
based on name , role (obviously). did in 2 steps, below, have think there's 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!
var dict = people.tolookup(p=>p.name, p=>p.role) .todictionary(it=>it.key, it=>it.tolist());
Comments
Post a Comment