Unity&C#/C#

[C#] Orderby

리네엔 2024. 10. 14. 22:36

What is Orderby Function?

  • 배열이나 리스트의 각 요소에 대해 "정렬 기준"을 하나 설정하고, 그 기준에 맞게 오름차순으로 정렬하는 함수
  1. 숫자 리스트를 오름차순으로 정렬

    int[] numbers = {5,2,9,1,6};
    int[] sorted = numbers.OrderBy(x=>x).ToArray();
    // 결과=> numbers : {1,2,5,6,9}
  2. 객체 리스트를 특정 필드를 기준으로 정렬

    class Person{
     public sring Name {get;set;}
     public int Age{get;set;}
    }
    List<Person> people = new List<Person>{
     new Person{Name="Alice", Age = 30},
     new Person{Name="Bob", Age = 25},
     new Person{Name="Charlie", Age = 35},
    }
    List<Person> people = people.OrderBy(p=> p.Age).ToList()
    // 결과: Bob(25), Alice(30), Charlie(35)
  3. OrderBy와 Random의 조합

    int[] numbers = {5,2,9,1};
    int[] sorted = numbers.OrderBy(x=>Random.Range(0f,7f)).ToArray();
  • 5에 대해 Random.Range(0f,7f)3.4를 생성
  • 2에 대해 Random.Range(0f,7f)6.2를 생성
  • 9에 대해 Random.Range(0f,7f)1.1를 생성
  • 1에 대해 Random.Range(0f,7f)4.8를 생성
    이 값을 기준으로 1.1 -> 3.4 -> 4.8 -> 6.2 순으로 정렬
    // 결과
    {9, 5, 1, 2}

'Unity&C# > C#' 카테고리의 다른 글

[C#] Reflection  (0) 2024.10.14
[C#] Enum  (0) 2024.10.14
[C#] Abstract Class  (0) 2024.10.14
[기본] 참조(얕은 복사)  (1) 2022.09.20
[C#문법] Dictionary  (0) 2022.08.31