title: C# Distinct on IEnumerable<T> with custom IEqualityComparer
body: <p>Here's what I'm trying to do. I'm querying an XML file using LINQ to XML, which gives me an IEnumerable<code>&lt;T</code>> object, where T is my "Village" class, filled with the results of this query. Some results are duplicated, so I would like to perform a Distinct() on the IEnumerable object, like so:</p>
  
  <pre><code>public IEnumerable&lt;Village&gt; GetAllAlliances()
  {
      try
      {
          IEnumerable&lt;Village&gt; alliances =
               from alliance in xmlDoc.Elements("Village")
               where alliance.Element("AllianceName").Value != String.Empty
               orderby alliance.Element("AllianceName").Value
               select new Village
               {
                   AllianceName = alliance.Element("AllianceName").Value
               };
  
          // TODO: make it work...
          return alliances.Distinct(new AllianceComparer());
      }
      catch (Exception ex)
      {
          throw new Exception("GetAllAlliances", ex);
      }
  }
  </code></pre>
  
  <p>As the default comparer would not work for the Village object, I implemented a custom one, as seen here in the AllianceComparer class:</p>
  
  <pre><code>public class AllianceComparer : IEqualityComparer&lt;Village&gt;
  {
      #region IEqualityComparer&lt;Village&gt; Members
      bool IEqualityComparer&lt;Village&gt;.Equals(Village x, Village y)
      {
          // Check whether the compared objects reference the same data.
          if (Object.ReferenceEquals(x, y)) 
              return true;
  
          // Check whether any of the compared objects is null.
          if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
              return false;
  
          return x.AllianceName == y.AllianceName;
      }
  
      int IEqualityComparer&lt;Village&gt;.GetHashCode(Village obj)
      {
          return obj.GetHashCode();
      }
      #endregion
  }
  </code></pre>
  
  <p>The Distinct() method doesn't work, as I have exactly the same number of results with or without it. Another thing, and I don't know if it's usually possible, but I cannot step into AllianceComparer.Equals() to see what could be the problem.<br/>
  I've found examples of this on the Internet, but I can't seem to make my implementation work.</p>
  
  <p>Hopefully, someone here might see what could be wrong here!
  Thanks in advance!</p>