在N列表中查找公共对象

我有N个“人物”清单。 人们有2个属性: IdName 。 我想找到所有N个列表中包含的人员。 我只想在Id上匹配。

以下是我的出发点:

 List result = new List(); //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 list in peoplesList.Skip(1)) { //Do I even need this? } } 

我被困在试图把头包裹在中间部分。 我只想要来自peoplesList.Skip(1)每个列表中的peoplesList.Skip(1)

数学上讲; 您正在寻找所有列表之间的集合交集。 幸运的是,LINQ有一个Instersect方法,所以你可以迭代地交叉你的集合。

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

要使“ID”选择器工作,您需要为People实现IEqualityComparer

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

IEqualityComparer实际实现因其非常简单而遗漏了。