GroupBy和IEqualityComparer< TKey>比较器 [英] GroupBy and IEqualityComparer<TKey> comparer

查看:108
本文介绍了GroupBy和IEqualityComparer< TKey>比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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:

  1. 它使用现有键的哈希码(使用GetHashCode)检查项目的哈希码.如果不等于这些值中的任何一个,则会将其添加到新组中
  2. 如果找到匹配的哈希码,则然后检查是否相等(使用Equals).如果该项目等于"组密钥,则将该项目添加到该组.
  1. 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
  2. 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类本身是否实现IEquatableEqualsGetHashCode的任何适用替代.

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.

因此,这暗示了EqualsGetHashCode之间的一些关键关系:

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&lt; TKey&gt;比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆