development

목록 정렬

big-blog 2020. 11. 22. 20:02
반응형

목록 정렬


C #을 사용하여 목록을 숫자로 정렬하는 가장 좋은 방법은 무엇입니까? 내 목록에는 항목 5,7,3이 있으며 3,5,7로 정렬하고 싶습니다. 나는 더 긴 방법을 알고 있지만 linq가 더 빠른 방법을 상상할 수 있습니까?

미안해 이것이 하루의 끝이었고 내 마음은 그것이 효과가 있었던 다른 곳이며 처음에는 변경되지 않았습니다. (


여기에서는 LINQ가 필요하지 않습니다. Sort를 호출하기 만하면됩니다.

list.Sort();

예제 코드 :

List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
    Console.WriteLine(x);
}

결과:

3
5
7

단순하게 유지하는 것이 핵심입니다.

아래에서 시도하십시오.

var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();

var values = new int[] {5,7,3};
var sortedValues = values.OrderBy(v => v).ToList();   // result 3,5,7

List<int> list = new List<int> { 5, 7, 3 };  
list.Sort((x,y)=> y.CompareTo(x));  
list.ForEach(action => { Console.Write(action + " "); });

내림차순으로 정수 목록 정렬

class Program
    {       
        private class SortIntDescending : IComparer<int>
        {
            int IComparer<int>.Compare(int a, int b) //implement Compare
            {              
                if (a > b)
                    return -1; //normally greater than = 1
                if (a < b)
                    return 1; // normally smaller than = -1
                else
                    return 0; // equal
            }
        }

        static List<int> intlist = new List<int>(); // make a list

        static void Main(string[] args)
        {
            intlist.Add(5); //fill the list with 5 ints
            intlist.Add(3);
            intlist.Add(5);
            intlist.Add(15);
            intlist.Add(7);

            Console.WriteLine("Unsorted list :");
            Printlist(intlist);

            Console.WriteLine();
            // intlist.Sort(); uses the default Comparer, which is ascending
            intlist.Sort(new SortIntDescending()); //sort descending

            Console.WriteLine("Sorted descending list :");
            Printlist(intlist);

            Console.ReadKey(); //wait for keydown
        }

        static void Printlist(List<int> L)
        {
            foreach (int i in L) //print on the console
            {
                Console.WriteLine(i);
            }
        }
    }

int 내림차순 정렬 목록은 먼저 정렬하고 반대로 할 수 있습니다.

class Program
{
    static void Main(string[] args)
    {

        List<int> myList = new List<int>();

        myList.Add(38);
        myList.Add(34);
        myList.Add(35);
        myList.Add(36);
        myList.Add(37);


        myList.Sort();
        myList.Reverse();
        myList.ForEach(Console.WriteLine);


    }



}

double jhon = 3;
double[] numbers = new double[3];
for (int i = 0; i < 3; i++)

{
    numbers[i] = double.Parse(Console.ReadLine());

}
Console.WriteLine("\n");

Array.Sort(numbers);

for (int i = 0; i < 3; i++)
{
    Console.WriteLine(numbers[i]);

}

Console.ReadLine();

참고 URL : https://stackoverflow.com/questions/3738639/sorting-a-listint

반응형