8

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.

Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

12

LINQ:

pointsOfList = pointsOfList.OrderByDescending(p => p.X).ToList();
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
12
pointsOfList.OrderBy(p=>p.x).ThenBy(p=>p.y)
Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
  • I may be wrong on this, but you'd have to assign a value to it, correct? – Dan Drews May 21 '13 at 22:52
  • 2
    Did 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. – Ronan Thibaudau Jan 16 '15 at 22:51
1

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);
    }
}
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480