Cannot exclude from a list items contained in another list with Linq
I have two lists of custom types "Client". I have to merge the two lists avoiding possibnormale duplicates.
I tried both IEnumerable.Except() method and the "NOT IN" statement via Linq but the returned list has still the elements contained in the other list:var dupes = getFirstList().ToList(); //List<Client>
var search = getUsersList().Cast<Client>().ToList(); //List<Client>
//The returned items are the same as in original dupes list
var unique = dupes.Except(search).ToList();
//No records are returned, even if debugging I can see that same contactId is in both lists
var u = from k in normalSearch
where !(from d in dupes
select d.ContactId)
.Contains(k.ContactId)
select k;
Why I cannot match the two lists to remove duplicates?
EDIT:
For Except method I guess I have to implement the Interfa开发者_JAVA百科ce IEquatable to let it work with custom types. But in the case of LINQ statement I still cannot understand why no record is returned, since "ContactId" field is an int in this case.
For the linq part (which will be slow as compared to Except) you can try something
from k in search
where !dupes.Any(d => d.ContactId == k.ContactId)
select k;
Except used this way is checking reference equality, so it doesn't matter if those objects have the same ContactId
or any other fields. (in your code you are using normalSearch
variable but it's no where there defined)
精彩评论