C# List Sort. I have a question

Asked 2 years ago, Updated 2 years ago, 40 views

There is a class called abc. This is the class that gets the coordinate information of the click point.

List pts = new List();

So, if you put it in the list, the information is as follows.

alt text

The coordinates of each X and Y are included as double values.

Currently, it will be listed in the order you click.

Not in the order you click

I'd like to change the order of the list based on X coordinates, so I would appreciate it if you could tell me

[1] [0] [5] [2] [3] [4] I want to change the order.

Thank you. Have a nice day~

.net c#

2022-09-21 18:07

2 Answers

Why don't we use linq?

var test = from n in pts
           orderby n.X ascending
           select n;


2022-09-21 18:07

You can use the Sort method in the List. You can specify the sorting criteria.

using System;
using System.Collections.Generic;

class Solution
{
    static void Main(string[] args)
    {
        ABC p1 = new ABC();
        ABC p2 = new ABC();
        ABC p3 = new ABC();
        p1.x = 10.5f;p1.y = 15f;
        p2.x = 80.5f;p2.y = 5.7f;
        p3.x = 2.5f;p3.y = 37f;

        List<ABC> list = new List<ABC>();
        list.Add(p1);
        list.Add(p2);
        list.Add(p3);

        //This is how you sort it.
        This is the part that commands the sort to judge based on the //x value.
        list.Sort( (a,b) => a.x>b.x?1:-1);

        foreach(ABC item in list){
            Console.WriteLine(item.x+", "+item.y);
        }

    }
}

class ABC
{
    public float x;
    public float y;
}


2022-09-21 18:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.