总结委托中的IEqualityComparer [英] Wrap a delegate in an IEqualityComparer

查看:145
本文介绍了总结委托中的IEqualityComparer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

若干Linq.Enumerable功能需要一个的IEqualityComparer< T> 。是否有适应一个委托(T,T)=&GT方便的包装类;布尔实施的IEqualityComparer< T> ?这是很容易写一个(如果你忽略的问题确定一个正确的散列code),但我想知道是否有出位的现成的解决方案。

Several Linq.Enumerable functions take an IEqualityComparer<T>. Is there a convenient wrapper class that adapts a delegate(T,T)=>bool to implement IEqualityComparer<T>? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution.

具体而言,我想要做的设置操作词典 S,只用键定义的成员(同时根据不同的规则保留值)。

Specifically, I want to do set operations on Dictionarys, using only the Keys to define membership (while retaining the values according to different rules).

推荐答案

通常情况下,我会走这么解决了对答案评论@Sam(我已经在原来的职位做了一些编辑把它清理干净有点不改变的行为。)

Ordinarily, I'd get this resolved by commenting @Sam on the answer (I've done some editing on the original post to clean it up a bit without altering the behavior.)

下面是我的<一个即兴href="http://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer/270203#270203">@Sam's回答,用[IMNSHO]关键修复到默认的散列策略: -

The following is my riff of @Sam's answer, with a [IMNSHO] critical fix to the default hashing policy:-

class FuncEqualityComparer<T> : IEqualityComparer<T>
{
    readonly Func<T, T, bool> _comparer;
    readonly Func<T, int> _hash;

    public FuncEqualityComparer( Func<T, T, bool> comparer )
        : this( comparer, t => 0 ) // NB Cannot assume anything about how e.g., t.GetHashCode() interacts with the comparer's behavior
    {
    }

    public FuncEqualityComparer( Func<T, T, bool> comparer, Func<T, int> hash )
    {
        _comparer = comparer;
        _hash = hash;
    }

    public bool Equals( T x, T y )
    {
        return _comparer( x, y );
    }

    public int GetHashCode( T obj )
    {
        return _hash( obj );
    }
}

这篇关于总结委托中的IEqualityComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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