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?

spender
  • 117,338
  • 33
  • 229
  • 351

2 Answers2

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)
    );
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
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);
Ani
  • 111,048
  • 26
  • 262
  • 307
  • what if one of them is `null`? – Femaref Apr 25 '11 at 18:31
  • @Femaref: I would imagine that should be the delegate's problem. Anyway, I've put it an edit that should address that. – Ani Apr 25 '11 at 18:31
  • 2
    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... – spender Apr 25 '11 at 18:33