Find common objects in lists N

I have N People lists. People have 2 properties: Id and Name . I want to find people who are in all lists of N. I only want to combine the identifier.

Below is my starting point:

 List<People> result = new List<People>(); //I think I only need to find items in the first list that are in the others foreach (People person in peoplesList.First()) { //then this is the start of iterating through the other full lists foreach (List<People> list in peoplesList.Skip(1)) { //Do I even need this? } } 

I'm stuck trying to wrap my head around the middle part. I only need those that are on each list from peoplesList.Skip(1) .

+5
source share
1 answer

Mathematically speaking; You are looking for a set of intersections between all of your lists. Fortunately, LINQ has an Instersect method, so you can iteratively traverse your sets.

 List<List<People>> lists; //Initialize with your data IEnumerable<People> commonPeople = lists.First(); foreach (List<People> list in lists.Skip(1)) { commonPeople = commonPeople.Intersect(list); } //commonPeople is now an IEnumerable containing the intersection of all lists 

To start the "ID" selector, you need to implement IEqualityComparer for People

 IEqualityComparer<People> comparer = new PeopleComparer(); ... commonPeople = commonPeople.Intersect(list, comparer); 

The actual implementation of IEqualityComparer missing, as its pretty simple.

+4
source

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


All Articles