Sorting a point class list based on two C # values

I want to sort the list of 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 new to C #, and is there any similarity with the Java comparison methods that implement custom class mappers for classes, and also I would like to add a comparison method (int CompareTo) to the class sort by class.

Thanks in advance.

+4
source share
4 answers

Yes, you are 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 implementation of IComparable<Point> (and possibly not a common IComparable interface). If you want to implement the comparison elsewhere, run another IComparer<Point> class.

For equality, .NET also has IEquatable<T> and IEqualityComparer<T> . They are used for things like key comparisons in Dictionary<,> .

As an additional note, I highly recommend that you do not have public fields, and you might want to make readonly variables. (Optional types are generally easier to reason with.) You can also make Point a struct , not a class .

+8
source
 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); 
+3
source

You can implement the IComparable interface and implement it

 public int CompareTo( object obj ) 

in this method you can write logic to compare two objects, for example:

 if (objectA.x > objectB.x) return 1 else if (objectA.x < objectB.x) return -1 else // compare y in both objects 
+1
source

The interface you want to implement in C # is IComparable <T> , which acts like Java Comparable. Then your code will become

 public class Point : IComparable<Point> { private int x; private int y; public int X { get { return x; } } public int Y { get { return y; } } public Point(int xp, int yp) { x = xp; y = yp; } public int CompareTo(Point other) { // Custom comparison here } } 

Please note that I changed the public fields to private fields and changed the interface open with the interface to properties . This is more idiomatic C # - public fields are unhappy with both Java and C #.

0
source

Source: https://habr.com/ru/post/1433936/


All Articles