Exclude items from one list to another with different data types of objects, LINQ?

I have two lists filled with my own data. let's say there are two models Human and AnotherHuman . Each model contains different fields, but they have some common fields, such as LastName, FirstName, Birthday, PersonalID .

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

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

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

I tried to create a new list of duplicates 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(); 

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

Thanks in advance!

+6
source share
3 answers

Instead of creating new objects, how about checking properties as part of a 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(); 
+9
source
 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); 
+13
source
 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); 
+2
source

Source: https://habr.com/ru/post/956548/


All Articles