I am using lambda expressions to sort and search an array in C#. I don\'t want to implement the IComparer interface in my class, because I need to sort and search on multiple m
Try this:
public static class ComparisonEx
{
public static IComparer AsComparer(this Comparison @this)
{
if (@this == null)
throw new System.ArgumentNullException("Comparison @this");
return new ComparisonComparer(@this);
}
public static IComparer AsComparer(this Func @this)
{
if (@this == null)
throw new System.ArgumentNullException("Func @this");
return new ComparisonComparer((x, y) => @this(x, y));
}
private class ComparisonComparer : IComparer
{
public ComparisonComparer(Comparison comparison)
{
if (comparison == null)
throw new System.ArgumentNullException("comparison");
this.Comparison = comparison;
}
public int Compare(T x, T y)
{
return this.Comparison(x, y);
}
public Comparison Comparison { get; private set; }
}
}
It lets you use this code:
Comparison c = (x, y) => x == y ? 0 : (x <= y ? -1 : 1);
IComparer icc = c.AsComparer();
Func f = (x, y) => x == y ? 0 : (x <= y ? -1 : 1);
IComparer icf = f.AsComparer();