Sort 메서드를 사용하여 KeyValuePairs 컬렉션을 정렬합니다.
먼저 컬렉션을 설정하십시오 -
var myList = new List<KeyValuePair<int, int>>(); // adding elements myList.Add(new KeyValuePair<int, int>(1, 20)); myList.Add(new KeyValuePair<int, int>(2, 15)); myList.Add(new KeyValuePair<int, int>(3, 35)); myList.Add(new KeyValuePair<int, int>(4, 50)); myList.Add(new KeyValuePair<int, int>(5, 25));
정렬하려면 Sort() 메서드를 사용합니다. 이를 통해 우리는 CompareTo() 메서드를 사용하여 값을 비교했습니다 -
myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));
다음은 완전한 코드입니다 -
예시
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var myList = new List<KeyValuePair<int, int>>();
// adding elements
myList.Add(new KeyValuePair<int, int>(1, 20));
myList.Add(new KeyValuePair<int, int>(2, 15));
myList.Add(new KeyValuePair<int, int>(3, 35));
myList.Add(new KeyValuePair<int, int>(4, 50));
myList.Add(new KeyValuePair<int, int>(5, 25));
Console.WriteLine("Unsorted List...");
foreach (var val in myList) {
Console.WriteLine(val);
}
// Sort Value
myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));
Console.WriteLine("Sorted List...");
foreach (var val in myList) {
Console.WriteLine(val);
}
}
} 출력
Unsorted List... [1, 20] [2, 15] [3, 35] [4, 50] [5, 25] Sorted List... [4, 50] [3, 35] [5, 25] [1, 20] [2, 15]