We've Always Got Something to Say.

Read our thoughts on what's happening in the industry.

April 28 , 2010

Using .NET 3.5 List.Distinct()

by

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();

2 Responses to “Using .NET 3.5 List.Distinct()”

  1. joomla redakční systémwebdesigngrafikae-commerce…

    [...]Using .NET 3.5 List.Distinct() | Atlantic BT[...]…

  2. iluzjonista says:

    iluzjonista…

    [...]Using .NET 3.5 List.Distinct() | Atlantic BT[...]…

Leave a Reply

 

In a Nutshell

Since 1998, Atlantic BT has been a full service web development company that offers the tools, resources and services to get your business moving. We focus on combining new ideas, specific requirements, and years of experience into high-quality, results-oriented web solutions for small to medium sized businesses. If you want the best website possible that generates real results, let's get started.

Atlantic Business Technologies, Inc.
4509 Creedmoor Road, 3rd Floor
Raleigh, North Carolina 27612
  • Pinnacle Business Award Winner
  • Triangle Business Journal's Top 40 Under 40
  • Yahoo Search Marketing Ambassador
  • Google Adwords Qualified Company