I am trying to use an IComparer
to sort a list of Points. Here is the IComparer class:
public class CoordinatesBasedComparer : IComparer
{
public int Compare(Object q, Object r)
{
Point a = (p)q;
Point b = (p)r;
if ((a.x == b.x) && (a.y == b.y))
return 0;
if ((a.x < b.x) || ((a.x == b.x) && (a.y < b.y)))
return -1;
return 1;
}
}
In the client code, I am trying to using this class for sorting a list of points p (of type List<Point>
):
CoordinatesBasedComparer c = new CoordinatesBasedComparer();
Points.Sort(c);
The code errors out. Apparently it is expecting IComparer<Point>
as argument to sort method.
What do I need to do to fix this?
If you're slow like me, the -1 and 1 can be difficult to reason about when using
IComparer
. The way to think about it is whenx
should go first, return -1. Wheny
should go first, return 1.It can still get confusing if you have lots of fields to sort by. You can use an
Enum
to make your comparison logic more readable than 1 and -1, then cast the result.This example puts objects with the least amount of null fields in the front.
I was getting an
InvalidOperation
error while adding an object of typeMyClass
to aSortedList<MyClass>
. I was, incorrectly, implementing the IComparer interface. What I needed to implement was IComparable with the method CompareTo(MyClass other), instead of the ICompare.Compare(MyClass x, MyClass y). This is a simplified example:This fixed it:
This was broken (don't do this if adding to
SortedList<MyClass>
):This was the error:
You need to implement the strongly type interface (MSDN).
BTW, I think you use too many braces, I believe they should be used only when they contribute to the compiler. This is my version:
Just like I dislike people using
return (0)
.Note that if you target a .Net-3.5+ application you can use LINQ which is easier and even faster with sorting.
LINQ vesion can be something like: