简体   繁体   English

GroupBy 和 IEqualityComparer<TKey> 比较器

[英]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实例是否与现有组的键“相等”,因此应该在该组中:

  1. It checks the hash code of the item (using GetHashCode ) against the hash code of existing keys.它根据现有键的哈希码检查项目的哈希码(使用GetHashCode )。 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 ).如果找到匹配的哈希码,则它检查相等性(使用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 :所以这意味着EqualsGetHashCode之间的一些关键关系:

  • 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.相反的是不正确的-具有相同的散列码不必等于两个项目。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM