How to sort List<Point>
21,644
Solution 1
LINQ:
pointsOfList = pointsOfList.OrderByDescending(p => p.X).ToList();
Solution 2
pointsOfList.OrderBy(p=>p.x).ThenBy(p=>p.y)
Solution 3
This simple Console program does that:
class Program
{
static void Main(string[] args)
{
List<Points> pointsOfList = new List<Points>(){
new Points() { x = 9, y = 3},
new Points() { x = 4, y = 2},
new Points() { x = 1, y = 1}
};
foreach (var points in pointsOfList.OrderBy(p => p.x))
{
Console.WriteLine(points.ToString());
}
Console.ReadKey();
}
}
class Points
{
public int x { get; set; }
public int y { get; set; }
public override string ToString()
{
return string.Format("({0}, {1})", x, y);
}
}
Author by
Michael
Updated on May 22, 2020Comments
-
Michael almost 4 years
I have this variable:
List<Points> pointsOfList;
it's contain unsorted points( (x,y) - coordinates);
My question how can I sort the points in list by X descending.
for example:
I have this: (9,3)(4,2)(1,1)
I want to get this result: (1,1)(4,2)(9,3)
Thank you in advance.
-
Kirk Woll almost 11 yearsYour example shows the list sorted by X ascending.
-
-
Dan Drews almost 11 yearsI may be wrong on this, but you'd have to assign a value to it, correct?
-
Ronan Thibaudau over 9 yearsDid you instead mean "assign it to a value" and not "assign a value to it"? If so yes , the expression i noted evaluates to what was requested, he then need to keep going on it or store it or whatever he wants to do.