orderby 절(C# 참조)

업데이트: 2007년 11월

쿼리 식에서 orderby 절은 반환된 시퀀스 또는 오름차순이나 내림차순으로 정렬된 결과(그룹)를 보여 줍니다. 둘 이상의 보조 정렬 작업을 수행하기 위해 여러 개의 키를 지정할 수 있습니다. 요소의 형식에 대한 기본 비교자를 사용하여 정렬 작업을 수행합니다. 기본 정렬 순서는 오름차순입니다. 사용자 지정 비교자를 지정할 수도 있습니다. 그러나 메서드 기반 구문을 사용하는 경우에만 지정할 수 있습니다. 자세한 내용은 데이터 정렬을 참조하십시오.

예제

다음 예제에서 첫 번째 쿼리는 사전순으로 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);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
Ascending:
apple
blueberry
cherry

Descending:
cherry
blueberry
apple
*/

다음 예제에서는 학생의 성을 기준으로 기본 정렬을 수행한 다음 이름 순으로 두 번째 정렬을 수행합니다.

class OrderbySample2
{
    // The element type of the data source.
    public class Student
    {
        public string First { get; set; }
        public string Last { get; set; }
        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);
            }
        }

        // Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* 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 절은 OrderBy 메서드를 호출하여 변환됩니다. orderby 절의 여러 키는 ThenBy 메서드 호출을 변환합니다.

참고 항목

개념

LINQ 쿼리 식(C# 프로그래밍 가이드)

참조

group 절(C# 참조)

기타 리소스

C# 참조

쿼리 키워드(C# 참조)

C#에서 LINQ 시작