我有N个"人物"的清单。人们有2个属性:Id
和Name
。我想找到所有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?
}
}
我被困在试图将头围绕中间部分。我只想要peoplesList.Skip(1)
中每个列表中的内容。
答案 0 :(得分: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
要使“ID”选择器正常工作,您需要为IEqualityComparer
实施People
IEqualityComparer<People> comparer = new PeopleComparer();
...
commonPeople = commonPeople.Intersect(list, comparer);
IEqualityComparer
的实际实施因为非常简单而遗漏了。