2

I have a List<Points>() and I want to sort it with a custom comparer function.

I made:

public int MyCompare(Point p1, Point p2)
{
    ...
}

// In my main
// ...
points_.Sort(MyCompare); 
// ...

I works, all right.

Now I want to sort everything but the first element, so I thought to do:

points_.Sort(1, points_.Count()-1, MyCompare); 

But with this overload he wants as argument an IComparer.

How can I solve this?

Note that Point is not a custom class, it is from Xna framework. I don't want to implement a custom class with : IComparer

Francesco Bonizzi
  • 5,142
  • 6
  • 49
  • 88
  • 1
    "I don't want to implement a custom class with `: IComparer`". Why not? – Gjeltema Jun 23 '14 at 16:27
  • 1
    @Gjeltema There isn't a good reason, I'm just curious about how can I solve this without implement a custom class. – Francesco Bonizzi Jun 23 '14 at 16:28
  • @misiMe Write your own `Sort` function in that case based on some property of the `Point` class – DGibbs Jun 23 '14 at 16:29
  • The class that implements `IComparer` is typically a different class than the class being compared. It is like `String` and `StringComparer` in the framework. – Mike Zboray Jun 23 '14 at 16:36

2 Answers2

8

If you do not want to implement IComparer, you could create one from a delegate using the Comparer<T>.Create static method, like this:

points_.Sort(1, points_.Count()-1, Comparer.Create(MyCompare));

or even

points_.Sort(1, points_.Count()-1, Comparer.Create((a, b) => {
    ... // comparison logic goes here
}));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

As pointed out by @dasblinkenlight with .NET 4.5+ there's an ad-hoc method to convert a Comparison<T> delegate to an IComparer<T>.

But if you're stuck with a lower version, you can use this class to convert a Comparison<T> delegate to IComparer<T>:

    public class DelegateComparer<T> : IComparer<T>
    {
        private readonly Comparison<T> compDelegate;

        public DelegateComparer(Comparison<T> compDelegate)
        {
            if (compDelegate == null)
                throw new ArgumentNullException("compDelegate");
            this.compDelegate = compDelegate;
        }
        public int Compare(T x, T y)
        {
            return compDelegate(x, y);
        }
    }

Usage example:

points_.Sort(1, points_.Count()-1, new DelegateComparer<Point>(MyCompare)); 
digEmAll
  • 56,430
  • 9
  • 115
  • 140