Sort an array

sam

Member
Joined
Sep 8, 2016
Messages
10
Programming Experience
Beginner
how to sort list eg: I have point data {x1=153.25,y1=200}{x2=152.35,y2=200}{x3=151.75,y3=200}{x4=151.95,y4=200.5}{x5=151.75,y5=199.5}. For same value of y, x should be sorted in ascending order. for these list will be like {x5,y5; x3,y3; x4,y4; x1,y1; x2,y2}. I am new to c# thanks
 
The Array.Sort method is overloaded and allows you to sort arrays in various ways. The simplest way to do an ad hoc sort as you describe is by calling the overload that takes a Comparison<T> delegate:
C#:
Point[] points;

// ...

Array.Sort(points, (p1, p2) =>
{
    var result = p1.Y.CompareTo(p2.Y);

    if (result == 0)
    {
        result = p1.X.CompareTo(p2.X);
    }

    return result;
});
That code uses a Lambda expression to create the delegate. If you were to use a conventional named method, it would look like this:
C#:
private int ComparePoints(Point p1, Point p2)
{
    var result = p1.Y.CompareTo(p2.Y);

    if (result == 0)
    {
        result = p1.X.CompareTo(p2.X);
    }

    return result;
}
and
C#:
Point[] points;

// ...

Array.Sort(points, ComparePoints);
 
Last edited:

Latest posts

Back
Top Bottom