[C#, LINQ] OrderBy와 ThenBy로 숫자 배열 정렬하기

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

int[] temp1 = new int[] { 5 };
int[] temp2 = new int[] { 4 };
int[] temp3 = new int[] { 9 };
int[] temp4 = new int[] { 20 };
int[] temp5 = new int[] { 1 };

List<int[]> addarr = new();
addarr.Add(temp1);
addarr.Add(temp2);
addarr.Add(temp3);
addarr.Add(temp4);
addarr.Add(temp5);

IEnumerable<int[]> orderbyarr = addarr.OrderBy(x => x[0]);

foreach (int[] item in orderbyarr)
{
    Console.WriteLine(item[0]);
}

Console.WriteLine();

int[] temp_1 = new int[] { 20, 3 };
int[] temp_2 = new int[] { 5, 20 };
int[] temp_3 = new int[] { 4, 1 };
int[] temp_4 = new int[] { 9, 2 };
int[] temp_5 = new int[] { 20, 4 };
int[] temp_6 = new int[] { 20, 1 };
int[] temp_7 = new int[] { 4, 21 };

List<int[]> _addarr = new();
_addarr.Add(temp_1);
_addarr.Add(temp_2);
_addarr.Add(temp_3);
_addarr.Add(temp_4);
_addarr.Add(temp_5);
_addarr.Add(temp_6);
_addarr.Add(temp_7);

IEnumerable<int[]> _orderbyarr = _addarr.OrderBy(x => x[0]).ThenBy(x => x[1]); 

foreach (int[] item in _orderbyarr)
{
    Console.WriteLine($"{item[0]}, {item[1]}");
}

C#에는 LINQ라는 편리한 기능이 있어서 정렬을 쉽게 할 수 있습니다. 위 예제는 다차원 배열의 경우 각각의 원소에 대해서 정렬하고 싶을 때 ThenBy를 사용하는 예제입니다.

5개의 좋아요

알고리즘 문제를 풀고 있었는데 마침 @Vincent 님께서 힌트를 주셨네요.

using System;
using System.Linq;
using System.Text;

var N = int.Parse(Console.ReadLine());
var arr = new int[N][];
var sb = new StringBuilder();

for (var i = 0; i < N; i++)
{
    arr[i] = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
}

var sorted = arr.OrderBy(x => x[0]).ThenBy(x => x[1]).ToArray();

for (var i = 0; i < N; i++)
{
    for (var j = 0; j < 2; j++)
    {
        sb.Append($"{sorted[i][j]} ");
    }

    sb.AppendLine();
}

Console.WriteLine(sb);

감사합니다.

5개의 좋아요
var _orderbyarr = from item in _addarr
orderby item[0], item[1]
select item;

이게 되는 기적과 같은 언어는 여기밖에 없어요. 와우!

5개의 좋아요