LINQ: How to get distinct results based on a specific field

By Peter Bromberg

Occasionally you may want to filter some resultset to be distinct based on some particular field, such as an ID. Here's how to do it with a custom IEqualityComparer.

public class MyComparer : IEqualityComparer<IMyTypeSearchResult>
    {
         public bool Equals(IMyTypeSearchResult x, IMyTypeSearchResult y)
         {
             return x.SomeField == y.SomeField ;
        }

        public int GetHashCode(IMyTypeSearchResult  obj)
         {
             return obj.SomeField.GetHashCode();
        }
     }


// Usage (original SearchResults contains duplicates based on SomeField):

   container.SearchResults = container.SearchResults.Distinct( new MyComparer() );

NOTE: It is important for your GetHashCode method to return a meaningful unique Hash for your object. Sometimes it can be a good idea to combine more than one property and then return the GetHashCode result of the composite.

LINQ: How to get distinct results based on a specific field  (1650 Views)