在N列表中查找公共对象

5 c#

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

以下是我的出发点:

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?

    }
}
Run Code Online (Sandbox Code Playgroud)

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

Bra*_*NET 4

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

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
Run Code Online (Sandbox Code Playgroud)

为了让“ID”选择器工作,你需要IEqualityComparer实现People

IEqualityComparer<People> comparer = new PeopleComparer();
...
commonPeople = commonPeople.Intersect(list, comparer);
Run Code Online (Sandbox Code Playgroud)

IEqualityComparer省略的实际实现因为它非常简单。