# Sort an array

#### sam

##### Member
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:
thanks aton

Oops! I made a mistake in that code. I should have compared `result` to 0 rather than 1. I have corrected my previous post.

Replies
6
Views
967
Replies
1
Views
1K
Replies
2
Views
3K
Replies
2
Views
751
Replies
13
Views
1K