Getting Distinct Objects Using LINQ

If you try to get distinct objects using LINQ you have two choices. You can use the overload to Distinct, which takes an IComparer<> that you write, where you override Equals() and GetHashCode() or you can do a grouping and select the first object of each group. For example, at my work I work with a lot of Title objects. If I have some duplicates in my list I can’t just use Distinct(), because it will think every object is different, it doesn’t know how to determine what’s equal and what isn’t. Instead I would want to compare the Title Ids to check if they are different. You can do that like so

var distinctTitles = (from t in TitleList select t.Title).GroupBy(x => x.TitleId).Select(g => g.First());
|