Skip to content

Using .NET 3.5 List.Distinct()

When I was working on a project today, I had a List of objects where I needed to grab objects that had a distinct property value (i.e. where MyObject.MyID is distinct).

I discovered the Distinct() method on the List and I had never used it before so I wasn’t sure of the syntax. After further review, I learned you can use the IEqualityComparer interface to specify how to determine if the object is distinct.

I’ll just show you the code because I feel it’s self explanatory:

public class MyObjectMyIDComparer : IEqualityComparer
  public bool Equals(MyObject x, MyObject y)
    return x.MyID == y.MyID;

  public int GetHashCode(MyObject obj)
    return obj.ToString().GetHashCode();

Now you can call the Distinct() method and pass in the class:

List MyObjectDistinctMyIDList = MyObjectList.Distinct(new MyObjectMyIDComparer()).ToList();

The Atlantic BT Manifesto

The Ultimate Guide To Planning A Complex Web Project