C# Distinct on IEnumerable with custom IEqualityComparer

后端 未结 3 1872
别跟我提以往
别跟我提以往 2020-12-07 18:41

Here\'s what I\'m trying to do. I\'m querying an XML file using LINQ to XML, which gives me an IEnumerable> object, where T is my \"Village\" class, filled

相关标签:
3条回答
  • 2020-12-07 19:18

    Or change the line

    return alliances.Distinct(new AllianceComparer());
    

    to

    return alliances.Select(v => v.AllianceName).Distinct();
    
    0 讨论(0)
  • 2020-12-07 19:27

    return alliances.Select(v => v.AllianceName).Distinct();

    That would return an IEnumerable<string> instead of IEnumerable<Village>.

    0 讨论(0)
  • 2020-12-07 19:30

    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.

    0 讨论(0)
提交回复
热议问题