Distinct not working in Linq-to-Objects

   I was developing a project that I have and came to the point where I needed to find only the distinct elements of a specific IEnumerable, and that’s when I looked a bit closely to the Distinct Extension Method for IEnumerable, so ok, let me use it, this is just what I need so this should be fairly simple (This was my first mistake. Thinking something should be simple. Shame on me. Smile ).

  Ok, so the Distinct Extension Method has only two overloads that are:

- One that takes no parameters:

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source);

- A second one that has 1 parameter:

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source,
 IEqualityComparer<TSource> comparer);
   - What? IEqualityComparer? Why not a Func<TSource, bool> like the others in the family?
  No problem, I just need to implement a IEqualityComparer, that shouldn’t be hard. 
  So I did the following:
    public class SampleComparer : IEqualityComparer<MyObject>
    {
        #region IEqualityComparer<MyObject> Members

        public bool Equals(MyObject x,MyObject y)
        {
            return x.Id.Equals(y.Id);
        }

        public int GetHashCode(MyObject obj)
        {
            return obj.GetHashCode();
        }

        #endregion
    }
  It sounds like almost too easy, but it’s done. So let’s use it.
var distinctResult = MyEnumerable.Distinct(new SampleComparer());
  Done, so now I just have my distinct results, right? NO. WHAT? WHY NOT?
  So I found out that Distinct isn’t really working, so what can I use? Why not GroupBy. 
  So I did the following code:
var distinctEntities = MyEnumerable.GroupBy(element => element.Name);
 Damn this gives me a IEnumerable<IGrouping<string, Element>> and I just want a list elements now.
  So there we go again:
var distinctEntities = MyEnumerable.GroupBy(element => element.Name)
  .Select(group => group.First());
  And now I have a real list of the distinct elements inside my IEnumerable.

No Comments