[英]GroupBy and IEqualityComparer<TKey> comparer
I was going through the GroupBy method in LINQ :我正在 LINQ 中通过 GroupBy 方法:
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer
)
I understand how to use GroupBy and what it returns.我了解如何使用 GroupBy 及其返回的内容。 I want to understand the significance of
IEqualityComparer<TKey> comparer
and what is it actually used for in GroupBy.我想了解
IEqualityComparer<TKey> comparer
的重要性以及它在 GroupBy 中的实际用途。
The IEqualityComparer<TKey>
object will be used to perform a two-step check to see if a TKey
instance is "equal" to the key of an existing group and thus should be in that group: IEqualityComparer<TKey>
对象将用于执行两步检查,以查看TKey
实例是否与现有组的键“相等”,因此应该在该组中:
GetHashCode
) against the hash code of existing keys.GetHashCode
)。 If it does not equal any of those values it is added to a new groupEquals
).Equals
)。 If the item is "equal to" the group key, the item is added to that group. If you do not supply a comparer (either by passing null
or using one of the overloads that does not have that parameter), the "default" comparer is used, which uses the TKey
class itself if it implements IEquatable
or any applicable overrides of Equals
and GetHashCode
.如果您不提供比较器(通过传递
null
或使用没有该参数的重载之一),则使用“默认”比较器,如果它实现了IEquatable
或任何适用的Equals
覆盖,则使用TKey
类本身和GetHashCode
。
So this implies a few key relationships between Equals
and GetHashCode
:所以这意味着
Equals
和GetHashCode
之间的一些关键关系:
You've provided a nonsensical equality comparer, so your results are going to be nonsensical.您提供了一个无意义的平等比较器,因此您的结果将是无意义的。 Your hash code is based on the reference to the comparer itself, which has nothing to do with anything in your
Equals
method, and in your Equals
method you're saying that two objects are equal if the first object is as long or longer than the second string.您的哈希码基于对比较器本身的引用,这与您的
Equals
方法中的任何内容无关,并且在您的Equals
方法中,如果第一个对象与第二个字符串。 This just makes no sense, it even violates basic properties of equality in that the order of the parameters should be irrelevant.这毫无意义,它甚至违反了等式的基本属性,因为参数的顺序应该无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.