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

标签 c# asp.net-mvc linq list

我有两个列表,其中填充了它们自己的数据。 假设有两个模型 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/

相关文章:

c# - IEnumerable<XAttribute> 返回 Null,需要返回属性值

c# - 通过 LINQ 从索引迭代中获得 yield

c# - 使用 XmlDocument 导出 Excel 表格的 XML

c# - 是否可以在 LINQ 中创建相关子查询?

c# - 检查数据读取器是否为空

javascript - ASP.NET MVC路由和路径是js文件

c# - ValidateAntiForgeryToken token 有效但不匹配

asp.net-mvc - 我可以远程调试托管在 Pivotal Cloud Foundry 上的 ASP.net 应用程序吗?

c# - 错误 MSB3823 : Non-string resources require the property GenerateResourceUsePreserializedResources to be set to true

c# - 为什么自动选择列表框的最后一项?