GroupBy和IEqualityComparer< TKey>比较器 [英] GroupBy and IEqualityComparer<TKey> comparer
问题描述
我正在使用LINQ中的GroupBy方法:
I was going through the GroupBy method in LINQ :
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer
)
我了解如何使用GroupBy及其返回的内容.我想了解IEqualityComparer<TKey> comparer
的含义及其在GroupBy中的实际用途.
I understand how to use GroupBy and what it returns. I want to understand the significance of IEqualityComparer<TKey> comparer
and what is it actually used for in GroupBy.
推荐答案
IEqualityComparer<TKey>
对象将用于执行两步检查,以查看TKey
实例是否与现有键相等"组,因此应该在该组中:
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:
- 它使用现有键的哈希码(使用
GetHashCode
)检查项目的哈希码.如果不等于这些值中的任何一个,则会将其添加到新组中 - 如果找到匹配的哈希码,则然后检查是否相等(使用
Equals
).如果该项目等于"组密钥,则将该项目添加到该组.
- It checks the hash code of the item (using
GetHashCode
) against the hash code of existing keys. If it does not equal any of those values it is added to a new group - If a matching hash code is found, it then checks for equality (using
Equals
). If the item is "equal to" the group key, the item is added to that group.
如果您不提供比较器(通过传递null
或使用不具有该参数的重载之一),则使用默认"比较器,该比较器使用TKey
类本身是否实现IEquatable
或Equals
和GetHashCode
的任何适用替代.
If you do not supply a comparer (either by passing null
or using one of the overloads that does not have that parameter), the "deafult" comparer is used, which uses the TKey
class itself if it implements IEquatable
or any applicable overrides of Equals
and GetHashCode
.
因此,这暗示了Equals
和GetHashCode
之间的一些关键关系:
So this implies a few key relationships between Equals
and GetHashCode
:
- 如果两个项目相等,则它们必须具有相同的哈希码.
- 相反的说法不正确-具有相同哈希码的两个项目必须不相等.
- If two items are equal, they must have the same hash code.
- The opposite is not true - two items that have the same hash code do not have to be equal.
这篇关于GroupBy和IEqualityComparer< TKey>比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!