16

我有两个列表,里面填满了他们自己的数据。假设有两个模型HumanAnotherHuman。每个模型都包含不同的字段,但是它们有一些共同的字段,例如LastName, FirstName, Birthday, PersonalID.

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

我想从 listanotherHumans中排除LastName, FirstName, Birthday所有等于 list 中任何项目的相应字段的项目humans

但是,如果列表中的任何项目与anotherHumans列表中的PersonalID项目humans相同PersonalID,则仅通过 this比较Human就足够了,否则通过.AnotherHumanPersonalIDLastName, FirstName and 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但是,如果它存在(它可以为空),我如何从两个列表中进行比较。有什么方法可以摆脱创建 AnotherHuman 的新实例和重复项列表并仅使用 LINQ 吗?

提前致谢!

4

3 回答 3

20

与其创建新对象,不如将属性作为 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();
于 2013-10-23T11:12:49.470 回答
18
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);
于 2013-10-23T11:44:29.557 回答
2
var nonIdItems = anotherHumans
   .Where(ah => !ah.PersonalID.HasValue)
   .Join(humans, 
         ah => new{ah.LastName, 
           ah.FirstName, 
           ah.Birthday}, 
         h => new{h.LastName, 
           h.FirstName, 
           h.Birthday}, 
         (ah,h) => ah);
var idItems = anotherHumans
   .Where(ah => ah.PersonalID.HasValue)
   .Join(humans, 
         ah => ah.PersonalID
         h => h.PersonalID, 
         (ah,h) => ah);
var allAnotherHumansWithMatchingHumans = nonIdItems.Concat(idItems);
var allAnotherHumansWithoutMatchingHumans = 
      anotherHumans.Except(allAnotherHumansWithMatchingHumans);
于 2013-10-23T11:14:14.300 回答