Gyu*_*l R 10 c# linq asp.net-mvc list
我有两个填充自己数据的列表.让我们说有两种型号Human和AnotherHuman.每个模型包含不同的字段,但它们有一些常见的字段,如LastName, FirstName, Birthday, PersonalID.
List<Human> humans = _unitOfWork.GetHumans();
List<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans();
Run Code Online (Sandbox Code Playgroud)
我想从列表anotherHumans中排除项目,这些项目LastName, FirstName, Birthday都等于列表中任何项目的相应字段humans.
但是,如果在任何项目anotherHumans列表具有PersonalID和列表项humans具有相同的PersonalID,那么它是足够的,比较Human有AnotherHuman这个只PersonalID,否则LastName, FirstName and Birthday.
我试图创建新的dublicates列表并将其排除在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();
Run Code Online (Sandbox Code Playgroud)
但是,我如何PersonalID从两个列表中比较它是否存在(可以为空).有没有办法摆脱创建AnotherHuman的新实例和重复列表并仅使用LINQ?
提前致谢!
Ser*_*kiy 15
var duplicates = from h in humans
from a in anotherHumans
where (h.PersonalID == a.PersonalID) ||
(h.LastName == a.LastName &&
h.FirstName == a.FirstName &&
h.Birthday == a.Birthday)
select a;
anotherHumans = anotherHumans.Except(duplicates);
Run Code Online (Sandbox Code Playgroud)
Nin*_*Nye 13
如何在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();
Run Code Online (Sandbox Code Playgroud)