LINQ: given a list of objects, create a dictionary with child objects in the form of keys and parent objects as value

I have these two classes

public class Person
{
}
public class Company
{
 public List<Person> Persons
{get;set;}
}

Objective: indicate a list of companies (i.e. List<Company> Companies). Create dictionarywith the key Person, and the list Companyit belongs to as values. Please note that one Personmay belong to several Companies.

I'm only interested in the LINQ solution; finding and collecting brute force is not what i want.

+3
source share
1 answer

I think this will do:

var dictionary = (from company in companies
                  from person in company.Persons
                  group company by person).ToDictionary(x => x.Key,
                                                        x => x.ToList());

Alternatively, use Lookup:

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()) ;

, " " - , LINQ, #. LINQ to SQL ( ..), , , .

+7

Source: https://habr.com/ru/post/1721358/


All Articles