Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Except() Method Does Not Work

I have 2 IList<T> of the same type of object ItemsDTO. I want to exclude one list from another. However this does not seem to be working for me and I was wondering why?

IList<ItemsDTO> related = itemsbl.GetRelatedItems();
IList<ItemsDTO> relating = itemsbl.GetRelatingItems().Except(related).ToList();

I'm trying to remove items in related from the relating list.

like image 486
Nugs Avatar asked Feb 15 '12 17:02

Nugs


2 Answers

Since class is a reference type, your ItemsDTO class must override Equals and GetHashCode for that to work.

like image 101
Magnus Avatar answered Oct 16 '22 10:10

Magnus


From MSDN:

Produces the set difference of two sequences by using the default equality comparer to compare values.

The default equality comparer is going to be a reference comparison. So if those lists are populated independently of each other, they may contain the same objects from your point of view but different references.

When you use LINQ against SQL Server you have the benefit of LINQ translating your LINQ statement to a SQL query that can perform logical equality for you based on primary keys or value comparitors. With LINQ to Objects you'll need to define what logical equality means to ItemsDTO. And that means overriding Equals() as well as GetHashCode().

like image 37
Yuck Avatar answered Oct 16 '22 08:10

Yuck