LINQ: Given A List of Objects, Create a Dictionary with child objects as keys and Parent Objects as Value
I have these two classes
public class Person
{
}
public class Company
{
public List<Person> Persons
{get;set;}
}
Challenge: Given a list of Company (i.e., List<Company> Companies
). Create a dictionary
with the key Person
, and a list of Company
he belongs to as the values. Note that one Person
can belong to mul开发者_运维知识库tiple Companies
.
I am only interested in LINQ solution; a brute force search and collect is not what I want.
I think this will do it:
var dictionary = (from company in companies
from person in company.Persons
group company by person).ToDictionary(x => x.Key,
x => x.ToList());
Alternatively, use a Lookup instead:
var lookup = company.SelectMany(company => company.Persons,
(company, person) => new { company, person })
.ToLookup(x => x.person, x => x.company)
.ToDictionary(x=>x.Key, x => x.ToList()) ;
Note that both of these are pretty much "brute force search and collect" - it's just that the code for that brute forcing is in LINQ instead of in C#. If you're using LINQ to SQL (etc) then it means the brute forcing may be done at the database of course.
精彩评论