GroupBy and IEqualityComparer<TKey> comparer

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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 ) 

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.

回答1:

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. 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.

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.

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.


回答2:

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. This just makes no sense, it even violates basic properties of equality in that the order of the parameters should be irrelevant.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!