Question

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();
    }
}
Was it helpful?

Solution 2

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();
            }
        }

OTHER TIPS

It would make sense to return the hash code of the Value of the element as you are using that to determine equality. Your GetHashCode() implementation must be consistent with your Equals() implementation.

public class XElementComparer : IEqualityComparer<XElement> {
    public bool Equals(XElement x, XElement y) {
        return x.Value == y.Value;
    }

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

You can also write something which will work for most of xml.

public class XElementComparer : IEqualityComparer<XElement>
{
    public bool Equals(XElement x, XElement y) 
    {
        return (x.FirstAttribute.Value.Equals(y.FirstAttribute.Value) 
                && x.LastAttribute.Value.Equals(y.LastAttribute.Value)); 
    } 

    public int GetHashCode(XElement x) 
    { 
        return x.Value.GetHashCode(); 
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top