How to use LINQ Distinct() with multiple fields

前端 未结 9 1378
借酒劲吻你
借酒劲吻你 2020-11-30 01:32

I have the following EF class derived from a database (simplified)

class Product
{ 
     public string ProductId;
     public string Product         


        
9条回答
  •  余生分开走
    2020-11-30 02:08

    Distinct method returns distinct elements from a sequence.

    If you take a look on its implementation with Reflector, you'll see that it creates DistinctIterator for your anonymous type. Distinct iterator adds elements to Set when enumerating over collection. This enumerator skips all elements which are already in Set. Set uses GetHashCode and Equals methods for defining if element already exists in Set.

    How GetHashCode and Equals implemented for anonymous type? As it stated on msdn:

    Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

    So, you definitely should have distinct anonymous objects, when iterating on distinct collection. And result does not depend on how many fields you use for your anonymous type.

提交回复
热议问题