tags:

views:

61

answers:

1

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 multiple Companies.

I am only interested in LINQ solution; a brute force search and collect is not what I want.

+4  A: 

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.

Jon Skeet