Linq - combining sublists from different objects into one object

I have an object that has a date and a list of people, a person has a first and last name. Something like:

PeopleInfo ---------- DateTime - StartDate List<Person> - People Person ------ string - FirstName string - LastName 

I have a list of people where there are several StartDates , each of which has its own list of people. Is it possible to combine them into one object using linq?

Example

 StartDate - 1/1/2011, People Bob, Sue, Jane StartDate - 2/2/2011, People Scott, Rob, Mark StartDate - 1/1/2011, People Fred, Gill, Jack 

Expected Result

 StartDate - 1/1/2011, People Bob, Sue, Jane, Fred, Gill, Jack StartDate - 2/2/2011, People Scott, Rob, Mark 

Is this possible in linq?

thanks

+7
source share
2 answers

You can do:

 List<PeopleInfo> peopleInfos = ... var merged = from peopleInfo in peopleInfos group peopleInfo by peopleInfo.StartDate into dateGroup select new PeopleInfo { StartDate = dateGroup.Key, People = dateGroup.SelectMany(pi => pi.People) .Distinct() .ToList() }; 

But it really looks like a hack; I would recommend that you create a container class in such a way as to prevent this "recurring date" scenario in the first place. for example, an implementation of ILookup<DateTime, Person> or IDictionary<DateTime, List<Person>> or HashSet<PeopleInfo> , which uses StartDate for equality.

+6
source
 ILookup<DateTime, Person> lookup = ( from pi in PeopleInfos from person in pi.People select new {StartDate = pi.StartDate, Person = person } ).ToLookup(x => x.StartDate, x => x.Person); 

OR

 List<PeopleInfo> list = ( from pi in PeopleInfos from person in pi.People group person by pi.StartDate into g select new PeopleInfo() { StartDate = g.Key, People = g.ToList() } ).ToList() 
+1
source

All Articles