Here\'s what I\'m trying to do. I\'m querying an XML file using LINQ to XML, which gives me an IEnumerable
Or change the line
return alliances.Distinct(new AllianceComparer());
to
return alliances.Select(v => v.AllianceName).Distinct();
return alliances.Select(v => v.AllianceName).Distinct();
That would return an IEnumerable<string>
instead of IEnumerable<Village>
.
The problem is with your GetHashCode
. You should alter it to return the hash code of AllianceName
instead.
int IEqualityComparer<Village>.GetHashCode(Village obj)
{
return obj.AllianceName.GetHashCode();
}
The thing is, if Equals
returns true
, the objects should have the same hash code which is not the case for different Village
objects with same AllianceName
. Since Distinct
works by building a hash table internally, you'll end up with equal objects that won't be matched at all due to different hash codes.
Similarly, to compare two files, if the hash of two files are not the same, you don't need to check the files themselves at all. They will be different. Otherwise, you'll continue to check to see if they are really the same or not. That's exactly what the hash table that Distinct
uses behaves.