gpt4 book ai didi

c# - 带有 Linq to XML 和 Distinct() 的 IEqualityComparer 不在代码中执行?

转载 作者:数据小太阳 更新时间:2023-10-29 02:27:34 25 4
gpt4 key购买 nike

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

最佳答案

返回元素的 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();
}
}

关于c# - 带有 Linq to XML 和 Distinct() 的 IEqualityComparer 不在代码中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7798229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com