Search code examples
c#xmllinqdistinctiequalitycomparer

IEqualityComparer with Linq to XML and Distinct() is not executed in code?


It doesnt matter what I write in the Equals method. The GetHashCode is always fired, but I do not know whose GetHashCode to return?

When the GetHashCode method is called then variable x has the following data:

In the first unitName elementName is the value "This is the value I want to compare" ...

<unit>
  <unitName>This is the value I want to compare</unitName>
  <units>
    <unit>
      <unitName>xxx</unitName>      
      <units>
        <unit>
          <unitName>cccc</unitName>
          <test>33</test>
          <test>44</test>                   
        </unit>
      </units>          
        </unit>
    </units>        
</unit>
IEnumerable<XElement> tempMemberList = doc.Elements("dep").Descendants("customers").Distinct(new XElementComparer());

public class XElementComparer : IEqualityComparer<XElement> {
    public bool Equals(XElement x, XElement y) {

        return x.Value == y.Value;
    }

    public int GetHashCode(XElement x) {
        return x.GetHashCode();
    }
}

Solution

  • This is the solution, I just had to get the proper value from the first unitName I wanted...

    public class XElementComparer : IEqualityComparer<XElement>
            {
                public bool Equals(XElement x, XElement y)
                {
                    string unitNameX = x.Element("unitName ").Value;
                    string unitNameY = y.Element("unitName ").Value;
                    return unitNameX == unitName Y;
                }
    
                public int GetHashCode(XElement x)
                {
                    string val = x.Element("unitName ").Value;
                    return val.GetHashCode();
                }
            }