Wrap a delegate in an IEqualityComparer

2019-01-02 16:52发布

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.

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

13条回答
何处买醉
2楼-- · 2019-01-02 17:36

I'm going to answer my own question. To treat Dictionaries as sets, the simplest method seems to be to apply set operations to dict.Keys, then convert back to Dictionaries with Enumerable.ToDictionary(...).

查看更多
登录 后发表回答