Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Given A List of Objects, Create a Dictionary with child objects as keys and Parent Objects as Value

Tags:

c#

linq

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.

like image 769
Graviton Avatar asked Nov 17 '25 19:11

Graviton


1 Answers

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.

like image 132
Jon Skeet Avatar answered Nov 20 '25 09:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!