I want to sort a List of the class Points in C# (See below) based first on x and then on y.
public class Point
{
public int x;
public int y;
public Point(int xp, int yp)
{
x = xp;
y = yp;
}
}
How do you do this: I am brand new to C#, and are there any similarities to Java compare methods that implement custom comparitors for classes, and also I would like to add the compare method (int CompareTo) to the class to sort on the class.
Thanks in advance.
Yes, you're looking for IComparable<T>
and IComparer<T>
- the latter is the equivalent of the Comparator<E>
interface in Java.
If you want to add a comparison to the Point
class itself, make Point
implement IComparable<Point>
(and possibly the non-generic IComparable
interface too). If you want to implement the comparison elsewhere, make another class implement IComparer<Point>
.
For equality, .NET also has IEquatable<T>
and IEqualityComparer<T>
. These are used for things like key comparisons in Dictionary<,>
.
As a side note, I'd strongly encourage you not to have public fields - and you may well want to make the variables readonly
. (Immutable types are generally easier to reason about.) You may decide to make Point
a struct
too, rather than a class
.
var points = new List<Point>() { new Point(1,3), new Point(1,4), new Point(1,2) };
var sortedPoints = points.OrderBy(point => point.x).ThenBy(point => point.y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With