C#/LINQ

[C#]LINQ 정렬 - OrderBy, OrderByDescending 메서드

DevStory 2022. 7. 17.

LINQ에서 정렬

이번 포스팅은 LINQ에서 추출된 데이터를 오름차순으로 정렬하는 OrderBy() 메서드와 내림차순으로 정렬하는 OrderByDescending() 메서드 사용 방법을 소개합니다.

 

OrderBy() 메서드와 OrderByDescending() 메서드에서 중요한 점은 데이터를 변경하는 것이 아니라 데이터의 순서만 변경한다는 점입니다.

 

그리고 OrderBy() 메서드와 OrderByDescending() 메서드는 메서드 구문에서 사용할 수 있으며, 질의 구문에서 데이터를 정렬하고 싶은 경우 orderby절을 사용합니다.

 

orderby절 뒤에 정렬하고자 하는 프로퍼티를 작성하고 내림차순으로 정렬하는 경우 descending 키워드를 명시합니다. 오름차순으로 정렬하는 경우 descending 키워드를 생략하거나 ascending 키워드를 명시합니다.


예제 1. int 타입의 List 정렬

다음 예제는 정렬되지 않은 int 타입의 List를 오름차순으로 정렬합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intArray = new List<int>() { 2, 4, 3, 5, 1, 0 };

    // 1. 질의 구문(Query Syntax) 
    List<int> linqQueryResult = (from    num in intArray
                                 orderby num
                                 select  num).ToList();

    // 2. 메서드 구문(Method Syntax)
    List<int> linqMethodResult = intArray.OrderBy(item => item).ToList();

    Console.WriteLine("질의 구문");
    foreach (int num in linqQueryResult)
      Console.Write(num + " ");

    Console.WriteLine("\n메서드 구문");
    foreach (int num in linqMethodResult)
      Console.Write(num + " ");
  }
}

 [실행 결과]

질의 구문
0 1 2 3 4 5
메서드 구문
0 1 2 3 4 5

내림차순으로 정렬하고 싶은 경우 질의 구문에는 descending 키워드를 명시하고 메서드 구문에서는 OrdeyByDescending() 메서드를 사용합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intArray = new List<int>() { 2, 4, 3, 5, 1, 0 };

    // 1. 질의 구문(Query Syntax) 
    List<int> linqQueryResult = (from    num in intArray
                                 orderby num descending
                                 select  num).ToList();

    // 2. 메서드 구문(Method Syntax)
    List<int> linqMethodResult = intArray.OrderByDescending(item => item).ToList();

    Console.WriteLine("질의 구문");
    foreach (int num in linqQueryResult)
      Console.Write(num + " ");

    Console.WriteLine("\n메서드 구문");
    foreach (int num in linqMethodResult)
      Console.Write(num + " ");
  }
}

[실행 결과]

질의 구문
5 4 3 2 1 0
메서드 구문
5 4 3 2 1 0

예제 2. string 타입의 List 정렬

다음 예제는 string 타입의 List를 오름차순으로 정렬합니다.

class Program
{
  static void Main(string[] args)
  {
    List<string> strArray = new List<string>() { 
      "Starbucks", "Costco", "P&G", "Apple", "Amazon",  
    };

    // 1. 질의 구문(Query Syntax) 
    List<string> linqQueryResult = (from    str in strArray
                                    orderby str ascending
                                    select  str).ToList();

    // 2. 메서드 구문(Method Syntax)
    List<string> linqMethodResult = strArray.OrderBy(item => item).ToList();

    Console.WriteLine("질의 구문");
    foreach (string str in linqQueryResult)
      Console.Write(str + " ");

    Console.WriteLine("\n메서드 구문");
    foreach (string str in linqMethodResult)
      Console.Write(str + " ");
  }
}

[실행 결과]

질의 구문
Amazon Apple Costco P&G Starbucks
메서드 구문
Amazon Apple Costco P&G Starbucks

내림차순으로 정렬하고 싶은 경우 int 타입과 마찬가지로 질의 구문에는 descending 키워드를 명시하고 메서드 구문에서는 OrderByDescending() 메서드를 사용합니다.

class Program
{
  static void Main(string[] args)
  {
    List<string> strArray = new List<string>() { 
      "Starbucks", "Costco", "P&G", "Apple", "Amazon",  
    };

    // 1. 질의 구문(Query Syntax) 
    List<string> linqQueryResult = (from    str in strArray
                                    orderby str descending
                                    select  str).ToList();

    // 2. 메서드 구문(Method Syntax)
    List<string> linqMethodResult = strArray.OrderByDescending(item => item).ToList();

    Console.WriteLine("질의 구문");
    foreach (string str in linqQueryResult)
      Console.Write(str + " ");

    Console.WriteLine("\n메서드 구문");
    foreach (string str in linqMethodResult)
      Console.Write(str + " ");
  }
}

[실행 결과]

질의 구문
Starbucks P&G Costco Apple Amazon
메서드 구문
Starbucks P&G Costco Apple Amazon

예제 3. 사용자 정의 클래스

다음 예제는 사용자 정의 클래스인 Person 타입의 List가 존재하고 Person 클래스의 나이(Age) 프로퍼티를 기준으로 데이터를 오름차순으로 정렬합니다.

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public override string ToString()
  {
    return "Name: " + Name + ", Age: " + Age;
  }
}

class Program
{
  static void Main(string[] args)
  {
    List<Person> listPerson = new List<Person>() { 
      new Person{ Name = "Tom",  Age=30},
      new Person{ Name = "Nick", Age=20},
      new Person{ Name = "Elsa", Age=28},
      new Person{ Name = "Jack", Age=15},
      new Person{ Name = "Sam",  Age=33}
    };

    // 1. 질의 구문(Query Syntax) 
    List<Person> linqQueryResult = (from    pesron in listPerson
                                    orderby pesron.Age
                                    select  pesron).ToList();

    // 2. 메서드 구문(Method Syntax)
    List<Person> linqMethodResult = listPerson.OrderBy(item => item.Age).ToList();

    Console.WriteLine("질의 구문");
    foreach (Person person in linqQueryResult)
      Console.WriteLine(person.ToString());

    Console.WriteLine("\n메서드 구문");
    foreach (Person person in linqMethodResult)
      Console.WriteLine(person.ToString());
  }
}

[실행 결과]

질의 구문
Name: Jack, Age: 15
Name: Nick, Age: 20
Name: Elsa, Age: 28
Name: Tom, Age: 30
Name: Sam, Age: 33

메서드 구문
Name: Jack, Age: 15
Name: Nick, Age: 20
Name: Elsa, Age: 28
Name: Tom, Age: 30
Name: Sam, Age: 33

내림차순으로 정렬하고 싶은 경우 질의 구문에서는 descending 키워드를 명시하고 메서드 구문에서는 OrderByDescending() 메서드를 사용합니다.


예제 4. Where절과 함께 사용

다음 예제는 Where절에서 필터된 데이터를 오름차순으로 정렬합니다.

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public override string ToString()
  {
    return "Name: " + Name + ", Age: " + Age;
  }
}

class Program
{
  static void Main(string[] args)
  {
    List<Person> listPerson = new List<Person>() { 
      new Person{ Name = "Tom",  Age=30},
      new Person{ Name = "Nick", Age=20},
      new Person{ Name = "Elsa", Age=28},
      new Person{ Name = "Jack", Age=15},
      new Person{ Name = "Sam",  Age=33}
    };

    // 1. 질의 구문(Query Syntax) 
    List<Person> linqQueryResult = (from    pesron in listPerson
                                    where   pesron.Age > 20
                                    orderby pesron.Age
                                    select  pesron).ToList();

    // 2. 메서드 구문(Method Syntax)
    List<Person> linqMethodResult = listPerson
        .Where(item => item.Age > 20)
        .OrderBy(item => item.Age)
        .ToList();

    Console.WriteLine("질의 구문");
    foreach (Person person in linqQueryResult)
      Console.WriteLine(person.ToString());

    Console.WriteLine("\n메서드 구문");
    foreach (Person person in linqMethodResult)
      Console.WriteLine(person.ToString());
  }
}

[실행 결과]

질의 구문
Name: Elsa, Age: 28
Name: Tom, Age: 30
Name: Sam, Age: 33

메서드 구문
Name: Elsa, Age: 28
Name: Tom, Age: 30
Name: Sam, Age: 33
반응형

댓글