IEqualityComparer with Linq to XML和Distinct()不在代码中执行

本文关键字:代码 执行 Distinct Linq with to XML IEqualityComparer | 更新日期: 2023-09-27 18:11:25

我在Equals方法中写什么并不重要。GetHashCode总是被触发,但我不知道谁的GetHashCode返回?

当调用GetHashCode方法时,变量x具有以下数据:

在第一个unitName中,elementName是值"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();
    }
}

IEqualityComparer with Linq to XML和Distinct()不在代码中执行

返回元素的Value的哈希码是有意义的,因为您正在使用它来确定相等性。您的GetHashCode()实施必须与您的Equals()实施一致。

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

这就是解决方案,我只需要从我想要的第一个unitName中获得适当的值…

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

你也可以写一些适用于大多数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(); 
    }
}