我有两个列表,其中填充了它们自己的数据。
假设有两个模型 Human
和 AnotherHuman
。每个模型都包含不同的字段,但是它们有一些通用字段,例如 LastName、FirstName、Birthday、PersonalID
。
List<Human> humans = _unitOfWork.GetHumans();
List<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans();
我想从列表 anotherHumans
中排除项目,其中 LastName, FirstName, Birthday
都等于列表 humans< 中任何项目的相应字段
.
然而,如果 anotherHumans
列表中的任何项目具有 PersonalID
并且列表 humans
中的项目具有相同的 PersonalID
,那么仅通过此 PersonalID
就足以将 Human
与 AnotherHuman
进行比较,否则通过 LastName、FirstName 和 Birthday
进行比较。
我尝试创建新的重复项列表并将其从 anotherHumans
中排除:
List<AnotherHuman> duplicates = new List<AnotherHuman>();
foreach(Human human in humans)
{
AnotherHuman newAnotherHuman = new AnotherHuman();
newAnotherHuman.LastName = human.LastName;
newAnotherHuman.Name= human.Name;
newAnotherHuman.Birthday= human.Birthday;
duplicates.Add(human)
}
anotherHumans = anotherHumans.Except(duplicates).ToList();
但是,如果 PersonalID
存在(可以为 null),我该如何比较这两个列表中的 PersonalID
。有没有办法摆脱创建 AnotherHuman 的新实例和重复项列表并仅使用 LINQ?
提前致谢!
最佳答案
与其创建新对象,不如将检查属性作为 linq 查询的一部分
List<Human> humans = _unitOfWork.GetHumans();
List<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans();
// Get all anotherHumans where the record does not exist in humans
var result = anotherHumans
.Where(ah => !humans.Any(h => h.LastName == ah.LastName
&& h.Name == ah.Name
&& h.Birthday == ah.Birthday
&& (!h.PersonalId.HasValue || h.PersonalId == ah.PersonalId)))
.ToList();
关于c# - 在另一个具有不同对象数据类型的列表中排除一个列表的项目,LINQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58749943/