带有 Linq to XML 和 Distinct() 的 IEqualityComparer 未在代码中执行?
我在 Equals 方法中写什么并不重要。 GetHashCode总是被触发,但我不知道GetHashCode返回谁?
当调用 GetHashCode 方法时,变量 x 具有以下数据:
在第一个 unitName elementName 中是值“这是我想要比较的值”...
<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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您使用元素的
Value
的哈希码来确定相等性时,返回它是有意义的。您的GetHashCode()
实现必须与您的Equals()
实现一致。It would make sense to return the hash code of the
Value
of the element as you are using that to determine equality. YourGetHashCode()
implementation must be consistent with yourEquals()
implementation.这就是解决方案,我只需从我想要的第一个 unitName 中获取正确的值......
This is the solution, I just had to get the proper value from the first unitName I wanted...
您还可以编写适用于大多数 xml 的内容。
You can also write something which will work for most of xml.