0

Out of interest how does the GetHashCode of a concrete implementation of IEqualityComparer work?

The reason that I ask is that I'm using linq to union two collections, and when only the left collection has an item GetHashCode is called twice. Further to that, it's called four times if both collections have one row.

This is rough typing but you'll get the point. GetHashCode is called twice, which I'm guessing is twice for the one item in listOne?

e.g.

var listOne = new List<SearchResult>{new SearchResult{Name="Blah"}}; 
var listTwo = new List<SearchResult>(); 

listOne.Union(listTwo, SearchResultComparer); 

public class SearchResultComparer : IEqualityComparer<SearchResult>
{
   public bool Equals(SearchResult x, SearchResult y){....}

   public int GetHashCode(SearchResult obj)
   {
       unchecked
       {
           int result = 0;
           result = (result * 397) ^ (obj.Name != null ?                 
           return result;
       }
   }

}

Thanks

4

1 回答 1

0

我很好奇你的观察,我只能观察GetHashCode每个列表中每个项目的一次检查。但就Union使用比较器的实现而言,可以这样想

static IEnumerable<T> Union<T>(this IEnumerable<T> first, IEnumerable<T> second, IEqualityComparer<T> comparer)
{        
    // there's undoubtedly validation against null sequences

    var unionSet = new HashSet<T>(comparer);

    foreach (T item in first)
    {
        if (unionSet.Add(item))
            yield return item;
    }

    foreach (T item in second)
    {
        if (unionSet.Add(item))
            yield return item;
    }
}

如果可以添加项目,则该Add方法将返回 true 或 false。HashSet在内部实现中,它会调用项目GetHashCode并获取值,然后查看该值是否已存在于集合中。如果是这样,它将每个与匹配的哈希码进行比较以确保相等。如果没有相等匹配(或者如果哈希码不存在),则成功添加项目并且该方法返回 true。否则,不添加该项目并且该方法返回 false。

于 2011-06-16T14:08:22.537 回答