gpt4 book ai didi

linq - Linq GroupBy 使用 Default EqualityComparer 的主要比较

转载 作者:行者123 更新时间:2023-12-03 13:59:54 26 4
gpt4 key购买 nike

我正在尝试使用显式键类型对某些对象执行 Linq GroupBy。我没有通过 IEqualityComparer到 GroupBy,所以根据文档:

The default equality comparer Default is used to compare keys.



它解释了 EqualityComparer<T>.Default像这样的属性(property):

The Default property checks whether type T implements the System.IEquatable<T> generic interface and if so returns an EqualityComparer<T> that uses that implementation.



在下面的代码中,我将 Fred 的数组分组。对象。他们有一个名为 FredKey 的 key 类型。 , 实现 IEquatable<FredKey> .

这应该足以使分组工作,但分组不起作用。在下面的最后一行中,我应该有 2 个组,但我没有,我只有 3 个包含 3 个输入项的组。

为什么分组不起作用?
class Fred
{
public string A;
public string B;
public FredKey Key
{
get { return new FredKey() { A = this.A }; }
}
}

class FredKey : IEquatable<FredKey>
{
public string A;
public bool Equals(FredKey other)
{
return A == other.A;
}
}

class Program
{
static void Main(string[] args)
{
var f = new Fred[]
{
new Fred {A = "hello", B = "frog"},
new Fred {A = "jim", B = "jog"},
new Fred {A = "hello", B = "bog"},
};

var groups = f.GroupBy(x => x.Key);
Debug.Assert(groups.Count() == 2); // <--- fails
}
}

最佳答案

来自 MSDN

If you implement IEquatable, you should also override the base class implementations of Object::Equals(Object) and GetHashCode() so that their behavior is consistent with that of the IEquatable::Equals method. If you do override Object::Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals() method return consistent results.



将此添加到 FredKey,它应该可以工作
public override int GetHashCode()
{
return A.GetHashCode();
}

关于linq - Linq GroupBy 使用 Default EqualityComparer 的主要比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1686307/

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