排除具有不同对象数据类型LINQ的另一个列表中的项吗? [英] Exclude items of one list in another with different object data types, LINQ?

查看:108
本文介绍了排除具有不同对象数据类型LINQ的另一个列表中的项吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个用自己的数据填充的列表. 可以说有两个模型HumanAnotherHuman.每个模型包含不同的字段,但是它们具有一些常见的字段,例如LastName, FirstName, Birthday, PersonalID.

I have two lists filled with their own data. lets say there are two models Human and AnotherHuman. Each model contains different fields, however they have some common fields like LastName, FirstName, Birthday, PersonalID.

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

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

I would like to exclude the items from list anotherHumans where LastName, FirstName, Birthday are all equal to the corresponding fields of any item in list humans.

但是,如果anotherHumans列表中的任何项目具有PersonalID并且列表humans中的项目具有相同的PersonalID,则仅通过此PersonalIDHumanAnotherHuman进行比较就足够了,否则按LastName, FirstName and Birthday.

However if any item in anotherHumans list has PersonalID and item in list humans have the same PersonalID, then it is enough to compare Human with AnotherHuman only by this PersonalID, otherwise by LastName, FirstName and Birthday.

我尝试创建新的重复列表并将其从anotherHumans中排除:

I tried to create new list of dublicates and exclude it from 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(它可以为空).有什么办法摆脱创建AnotherHuman的新实例和重复列表并仅使用LINQ的方法?

But how can I compare PersonalID from both lists if it presents (it is nullable). Is there any way to get rid from creating new instance of AnotherHuman and list of duplicates and use LINQ only?

提前谢谢!

推荐答案

与其创建新对象,不如在linq查询中检查属性

Instead of creating new objects, how about checking the properties as part of the linq query

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();

这篇关于排除具有不同对象数据类型LINQ的另一个列表中的项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆