gpt4 book ai didi

c# - 在另一个具有不同对象数据类型的列表中排除一个列表的项目,LINQ?

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:42 25 4
gpt4 key购买 nike

我有两个列表,其中填充了它们自己的数据。假设有两个模型 HumanAnotherHuman。每个模型都包含不同的字段,但是它们有一些通用字段,例如 LastName、FirstName、Birthday、PersonalID

List<Human> humans = _unitOfWork.GetHumans();
List<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans();

我想从列表 anotherHumans 中排除项目,其中 LastName, FirstName, Birthday 都等于列表 humans< 中任何项目的相应字段.

然而,如果 anotherHumans 列表中的任何项目具有 PersonalID 并且列表 humans 中的项目具有相同的 PersonalID,那么仅通过此 PersonalID 就足以将 HumanAnotherHuman 进行比较,否则通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com