Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of point class based on two values C#

Tags:

c#

class

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.

like image 551
CosmoRied Avatar asked Dec 11 '22 22:12

CosmoRied


2 Answers

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.

like image 79
Jon Skeet Avatar answered Dec 14 '22 11:12

Jon Skeet


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);
like image 31
armen.shimoon Avatar answered Dec 14 '22 10:12

armen.shimoon