LINQ Except () method not working

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

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

I am trying to remove items in relatedfrom a list relating.

+5
source share
4 answers

Since the class is a reference type, your class ItemsDTOmust override Equalsand GetHashCodeto do so.

+11
source

From MSDN :

It makes the specified difference between the two sequences, using the default value, compare the values.

- . , , , .

LINQ SQL Server, LINQ LINQ SQL-, . LINQ to Objects , ItemsDTO. Equals(), GetHashCode().

+1

, . , Ref, Equals GethashCode ItemsDTO,

0

I ran into the same problem. .NET seems to believe that the elements in one list are different from the same elements in another list (although they are actually the same). This is what I did to fix this:

Let your class inherit IEqualityComparer<T>, for example.

public class ItemsDTO: IEqualityComparer<ItemsDTO>
{
  public bool Equals(ItemsDTO x, ItemsDTO y)
  {
    if (x == null || y == null) return false;

    return ReferenceEquals(x, y) || (x.Id == y.Id); // In this example, treat the items as equal if they have the same Id
  }

  public int GetHashCode(ItemsDTO obj)
  {
    return this.Id.GetHashCode();
  }
}
0
source

All Articles