开发者

Quick IComparer?

Before I go reinventing the wheel, is there some framework way of creating an IComparer<T> from a Func<T,T,int>?

EDIT

IIRC (it's been a while) Java supports anonymous interface implementations. Does such a construct exist in C#开发者_如何转开发, or are delegates considered a complete alternative?


In the upcoming .NET4.5 (Visual Studio 2012) this is possible with the static factory method Comparer<>.Create. For example

IComparer<Person> comp = Comparer<Person>.Create(
    (p1, p2) => p1.Age.CompareTo(p2.Age)
    );


To my knowledge, there isn't such a converter available within the framework as of .NET 4.0. You could write one yourself, however:

public class ComparisonComparer<T> : Comparer<T>
{
    private readonly Func<T, T, int> _comparison;

    public MyComparer(Func<T, T, int> comparison)
    {
        if (comparison == null)
            throw new ArgumentNullException("comparison");

        _comparison = comparison;
    }

    public override int Compare(T x, T y)
    {
        return _comparison(x, y);
    }
}

EDIT: This of course assumes that the delegate can deal with null-arguments in a conformant way. If it doesn't, you can handle those within the comparer - for example by changing the body to:

if (x == null)
{
    return y == null ? 0 : -1;
}

if (y == null)
{
    return 1;
}

return _comparison(x, y);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜