문제 풀기/C#

47. (중요)문자열 내 마음대로 정렬하기(ThenBy, ThenByDescending 함수)

kagan-draca 2025. 2. 3. 15:26

 

기본틀 :

 

public class Solution {
    public string[] solution(string[] strings, int n) {
        string[] answer = new string[] {};
        return answer;
    }
}

 

풀이 1) 2중 반복문을 활용해 문자열의 index가 n인 문자를 비교 및 정렬하고, 같다면 사전 순으로 정렬한다.

using System;

public class Solution {
    public string[] solution(string[] strings, int n) 
    {
        for(int i = 0; i < strings.Length - 1; i++)
        {
            for(int j = i + 1; j < strings.Length; j++)
            {
                bool check = false;
                if((int)strings[i][n] > (int)strings[j][n]) check = true;
                else if((int)strings[i][n] == (int)strings[j][n] && String.Compare(strings[i], strings[j]) > 0) check = true;
                
                if(check)
                {
                    string temp = strings[i];
                    strings[i] = strings[j];
                    strings[j] = temp;  
                }
            }
        }
        return strings;
    }
}

 

풀이 2) OrderBy를 사용해 문자열의 index가 n인 문자를 기준으로 정렬 후,

ThenBy 함수로 정렬된 함수로 정렬된 기준으로 다시 정렬을 수행한다.

 

using System.Linq;

public class Solution {
    public string[] solution(string[] strings, int n) 
    {
        return strings.OrderBy(element => element[n]).ThenBy(element => element).ToArray();
    }
}

 

ThenBy, ThenByDescending 함수는 OrderBy, OrderByDescending으로

만들어진 정렬된 배열을 기준으로 다시 한 번 정렬을 하는데 사용된다.

 

만약, ThenBy나 ThenByDescending 함수가 아닌 OrderBy나 OrderByDescending을 2번 사용할 경우

 

마지막으로 호출된 OrderBy나 OrderByDescending으로만 정렬이 되지만

 

ThenBy, ThenByDescending은 앞 선 정렬을 기준으로 오름차순, 내림차순 정렬을 수행한다.

 

ex)

        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 25 },
            new Person { Name = "Bob", Age = 30 },
            new Person { Name = "Charlie", Age = 25 },
            new Person { Name = "Dave", Age = 30 },
            new Person { Name = "Eve", Age = 20 }
        };

이 있을 때,

 

        var sortedPeople = people
            .OrderBy(p => p.Age)      // 먼저 나이를 기준으로 정렬
            .ThenBy(p => p.Name);     // 나이가 같으면 이름으로 정렬

을 수행하면

 

Eve (20)
Alice (25)
Charlie (25)
Bob (30)
Dave (30)

//  나이를 기준으로 오름차순 정렬 후,
// 나이가 같다면 이름을 기준으로 오름차순 정렬한 것을 확인할 수 있다.

 

또한, ThenBy는

 

var sortedPeople = people
    .OrderBy(p => p.Age)
    .ThenBy(p => p.Name.Length)   // 이름 길이 오름차순 정렬
    .ThenByDescending(p => p.Name); // 이름 내림차순 정렬

 

위와 같이 여러 번 중첩해서 사용이 가능하다.