C#
 Computer >> コンピューター >  >> プログラミング >> C#

C#でKeyValuePairのコレクションをソートする方法

C#でKeyValuePairsコレクションを並べ替えるには、Sortメソッドを使用します。ラムダ式と組み合わせることで、キーまたは値を基準に柔軟にソートできます。

コレクションの準備

まず、KeyValuePairのリストを作成し、要素を追加しましょう。

var myList = new List<KeyValuePair<int, int>>();

// 要素の追加
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メソッドで並べ替える

並べ替えにはSort()メソッドを使用します。ここでは、CompareTo()メソッドを使ってValue(値)同士を比較しています。引数の順序を入れ替えることで、降順でのソートを実現しています。

myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));

なお、昇順でソートしたい場合は以下のように記述します。

myList.Sort((x, y) => (x.Value.CompareTo(y.Value)));

サンプルコード全体

以下は、ソート前とソート後のリストを表示する完全なコード例です。

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      var myList = new List<KeyValuePair<int, int>>();
      // 要素の追加
      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);
      }
      // 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]

このように、List<KeyValuePair<TKey, TValue>>に対してSort()メソッドとラムダ式を組み合わせれば、キー・値のどちらを基準とした並べ替えも簡単に実装できます。

  1. C#でヒープソートを実装する方法を徹底解説

    ヒープソートは、ヒープというデータ構造を利用したソートアルゴリズムです。ヒープのルート要素(最大値)を取り出して配列に格納し、その後、右端の葉要素と入れ替えてからヒープを再構築します。この操作をヒープが空になるまで繰り返すことで、配列が昇順にソートされます。 以下に、C#でヒープソートを実装したプログラムの例を示します。 サンプルコード using System; namespace HeapSortDemo { public class example { static void heapSort(int[] arr, int n) { fo

  2. C#でLINQのorderbyを使ってリストを並べ替える方法

    C#でリストを並べ替えるには、LINQのorderbyキーワードを使用します。orderbyを使うことで、指定した条件に基づいて要素を昇順または降順にソートできます。以下の例では、文字列の長さを基準にorderbyを設定しています。var myLen = from element in myList orderby element.Length select element;実際のコード例を見てみましょう。コード例using System; using System.Collections.Generic; using System.Linq; class Demo { static