Exclude items of one list in another with different object data types, LINQ?

后端 未结 3 1021
后悔当初
后悔当初 2020-12-30 05:35

I have two lists filled with their own data. lets say there are two models Human and AnotherHuman. Each model contains different fields, however th

相关标签:
3条回答
  • 2020-12-30 06:05
    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);
    
    0 讨论(0)
  • 2020-12-30 06:09
    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);
    
    0 讨论(0)
  • 2020-12-30 06:10

    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();
    
    0 讨论(0)
提交回复
热议问题