C#에서 시퀀스의 요소를 내림차순으로 정렬하려면 LINQ에서 제공하는 OrderByDescending() 메서드와 ThenBy() 메서드를 사용합니다. OrderByDescending()은 지정된 기준 키를 기준으로 요소를 내림차순으로 정렬하며, ThenBy()는 첫 번째 정렬 기준이 같은 요소들에 대해 2차 정렬 조건을 적용합니다.
다음과 같은 문자열 배열이 있다고 가정해 보겠습니다.
string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };이제 OrderByDescending()을 사용하여 요소를 내림차순으로 정렬합니다. 이때 각 문자열의 길이(Length)를 정렬 기준으로 삼고, 람다 식(Lambda Expression)을 함께 활용합니다. 이어서 ThenBy()를 적용하면 길이가 서로 같은 문자열들이 알파벳 순서로 2차 정렬됩니다.
IEnumerable<string> res = myStr.AsQueryable().OrderByDescending(ch => ch.Length).ThenBy(ch => ch);
위에서 설명한 내용을 모두 포함한 전체 예제 코드는 다음과 같습니다.
예제
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };
IEnumerable<string> res = myStr.AsQueryable().OrderByDescending(ch => ch.Length).ThenBy(ch => ch);
foreach (string arr in res)
Console.WriteLine(arr);
}
}
출력 결과
Keyboard
Monitor
Laptop
Mouse
결과 분석
실행 결과를 살펴보면, 각 문자열은 길이를 기준으로 내림차순 정렬되었습니다. 'Keyboard'와 'Monitor'는 길이가 8자로 동일하기 때문에 ThenBy()에 의해 알파벳 순서대로 'Keyboard'가 먼저 출력되고, 그다음 'Monitor'(8자), 'Laptop'(6자), 'Mouse'(5자) 순으로 나타납니다. 이처럼 OrderByDescending()과 ThenBy()를 조합하면 다중 조건 정렬도 손쉽게 구현할 수 있습니다.