orderby 절

orderby 절 (C# 참조)

쿼리 식에서 orderby 절은 반환되는 시퀀스나 하위 시퀀스(그룹)를 오름차순 또는 내림차순으로 정렬해 줘요. 정렬 키를 여러 개 지정하면 1차 정렬에 이어 2차, 3차… 보조 정렬도 함께 수행할 수 있고요. 기본 정렬은 요소 타입의 기본 비교자(default comparer)가 맡고, 기본 정렬 순서는 오름차순이에요. 사용자 지정 비교자를 쓰고 싶다면 메서드 기반 구문으로만 지정할 수 있어요. 자세한 내용은 Sorting Data에서 확인할 수 있어요.

출처: orderby clause (C# Reference)

본문

먼저 첫 번째 예시를 볼게요. 단어들을 A부터 시작하는 알파벳 순서로 정렬하고, 두 번째 예시에서는 같은 단어들을 내림차순으로 정렬해 봐요. 참고로 ascending 키워드는 기본 정렬 값이라 생략할 수 있어요.

class OrderbySample1
{
    static void Main()
    {
        // Create a delicious data source.
        string[] fruits = ["cherry", "apple", "blueberry"];

        // Query for ascending sort.
        IEnumerable<string> sortAscendingQuery =
            from fruit in fruits
            orderby fruit //"ascending" is default
            select fruit;

        // Query for descending sort.
        IEnumerable<string> sortDescendingQuery =
            from w in fruits
            orderby w descending
            select w;

        // Execute the query.
        Console.WriteLine("Ascending:");
        foreach (string s in sortAscendingQuery)
        {
            Console.WriteLine(s);
        }

        // Execute the query.
        Console.WriteLine(Environment.NewLine + "Descending:");
        foreach (string s in sortDescendingQuery)
        {
            Console.WriteLine(s);
        }
    }
}
/* Output:
Ascending:
apple
blueberry
cherry

Descending:
cherry
blueberry
apple
*/

다음 예시는 학생들의 성(last name)으로 1차 정렬을, 이름(first name)으로 2차 정렬을 수행해 봐요. 키를 쉼표로 나열하면 앞에서부터 순서대로 정렬 기준이 적용돼요.

class OrderbySample2
{
    // The element type of the data source.
    public class Student
    {
        public required string First { get; init; }
        public required string Last { get; init; }
        public int ID { get; set; }
    }

    public static List<Student> GetStudents()
    {
        // Use a collection initializer to create the data source. Note that each element
        //  in the list contains an inner sequence of scores.
        List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111},
           new Student {First="Claire", Last="O'Donnell", ID=112},
           new Student {First="Sven", Last="Mortensen", ID=113},
           new Student {First="Cesar", Last="Garcia", ID=114},
           new Student {First="Debra", Last="Garcia", ID=115}
        };

        return students;
    }
    static void Main(string[] args)
    {
        // Create the data source.
        List<Student> students = GetStudents();

        // Create the query.
        IEnumerable<Student> sortedStudents =
            from student in students
            orderby student.Last ascending, student.First ascending
            select student;

        // Execute the query.
        Console.WriteLine("sortedStudents:");
        foreach (Student student in sortedStudents)
            Console.WriteLine(student.Last + " " + student.First);

        // Now create groups and sort the groups. The query first sorts the names
        // of all students so that they will be in alphabetical order after they are
        // grouped. The second orderby sorts the group keys in alpha order.
        var sortedGroups =
            from student in students
            orderby student.Last, student.First
            group student by student.Last[0] into newGroup
            orderby newGroup.Key
            select newGroup;

        // Execute the query.
        Console.WriteLine(Environment.NewLine + "sortedGroups:");
        foreach (var studentGroup in sortedGroups)
        {
            Console.WriteLine(studentGroup.Key);
            foreach (var student in studentGroup)
            {
                Console.WriteLine("   {0}, {1}", student.Last, student.First);
            }
        }
    }
}
/* Output:
sortedStudents:
Garcia Cesar
Garcia Debra
Mortensen Sven
O'Donnell Claire
Omelchenko Svetlana

sortedGroups:
G
   Garcia, Cesar
   Garcia, Debra
M
   Mortensen, Sven
O
   O'Donnell, Claire
   Omelchenko, Svetlana
*/

컴파일 시점에 orderby 절은 xref:System.Linq.Enumerable.OrderBy* 메서드 호출로 변환돼요. 키가 여러 개인 orderby 절이라면 각각 xref:System.Linq.Enumerable.ThenBy* 메서드 호출로 변환됩니다.

더 알아보기