Distinct in Linq

Sometimes, in .net it can get a bit confusing about which interface you need to implement for to get object equality to work correctly. When using the Distinct extension method in Linq, IEqualityComparer<T> is very useful

var items = new List<Cheese>();
items.Add(new Cheese { Name = "Cheddar" });	
items.Add(new Cheese { Name = "Cheddar" });	
items.Add(new Cheese { Name = "Red Leicester" });	
items.Add(new Cheese { Name = "Stilton" });	
var distinct = items.Distinct();	

foreach (var item in distinct) {	
    Console.WriteLine (item.Name);	
}

//outputs
// Cheddar
// Cheddar
// Red Leicester
// Stilton

The key part is implementing GetHashCode so that the two objects will return the same hash code.

An example implementation:

class CheeseNameComparer : IEqualityComparer<Cheese> {	

 public bool Equals (Cheese x, Cheese y)	{ 
  return x.Name == y.Name;		
 }

 public int GetHashCode (Cheese obj) {
  return obj.Name.GetHashCode();
 }
}

distinct = items.Distinct(new CheeseNameComparer());
foreach (var item in distinct) {
  Console.WriteLine (item.Name);
} 
//outputs
// Cheddar
// Red Leicester
// Stilton
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
This entry was posted in Uncategorized. Bookmark the permalink.