Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# OrderBy 내림차순 정렬 완벽 가이드

C#에서 orderby ... descending 키워드를 사용하면 컬렉션의 요소들을 내림차순으로 손쉽게 정렬할 수 있습니다. LINQ 쿼리 구문에서 기본 정렬 방향은 오름차순이며, 내림차순으로 정렬하고 싶다면 반드시 descending 키워드를 함께 지정해야 합니다.

예제 데이터 준비

먼저 직원 정보를 담고 있는 리스트를 준비합니다.

IList<Employee> emp = new List<Employee>() {
new Employee() { EmployeeRank = 3, EmpName = "Tom", EmpMarks = 90 },
new Employee() { EmployeeRank = 4, EmpName = "Katie", EmpMarks = 95 }
};

OrderBy 내림차순 쿼리 작성

리스트를 직원 이름(EmpName) 기준으로 내림차순 정렬하려면 다음과 같이 orderby 절에 descending을 추가합니다.

var res = from str in emp
orderby str.EmpName descending
select str;

전체 예제 코드

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo {
public static void Main() {
IList<Employee> emp = new List<Employee>() {
new Employee() { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 },
new Employee() { EmployeeRank = 5, EmpName = "Raman", EmpMarks = 95 }
};

var res = from str in emp
orderby str.EmpName descending
select str;

Console.WriteLine("학생 목록 (내림차순):");
foreach (var list in res)
Console.WriteLine(list.EmpName);
}
}

public class Employee {
public int EmployeeRank { get; set; }
public string EmpName { get; set; }
public int EmpMarks { get; set; }
}

실행 결과

학생 목록 (내림차순):
Raman
Amit

메서드 구문(Method Syntax) 활용하기

쿼리 구문 대신 메서드 구문을 선호한다면 OrderByDescending() 확장 메서드를 사용하는 것이 좋습니다. 결과는 동일하며 코드가 더 간결해집니다.

var res = emp.OrderByDescending(str => str.EmpName);

정리

  • LINQ의 orderby는 기본적으로 오름차순으로 정렬됩니다.
  • 내림차순 정렬이 필요하면 descending 키워드를 명시해야 합니다.
  • 메서드 구문에서는 OrderByDescending()을 사용하면 됩니다.

이처럼 C#의 LINQ를 활용하면 복잡한 정렬 로직도 한 줄의 쿼리로 깔끔하게 처리할 수 있습니다.