Quick IComparer?
Asked Answered
L

2

10

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?

Lorentz answered 25/4, 2011 at 18:23 Comment(0)
G
4

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)
    );
Gardy answered 8/8, 2012 at 16:41 Comment(1)
That is such a useful addition, thanks for the info.Glomerate
S
3

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);
Slowwitted answered 25/4, 2011 at 18:29 Comment(3)
what if one of them is null?Dumuzi
@Femaref: I would imagine that should be the delegate's problem. Anyway, I've put it an edit that should address that.Slowwitted
Sure, the implementation is fairly trivial. My worry is that I have a quite a few snippets of code that replicate existing framework code. This seemed like one that should exist, but I couldn't find it...Lorentz

© 2022 - 2024 — McMap. All rights reserved.