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

C#のOrderedDictionaryでキーを含むICollectionを取得する方法

C#のOrderedDictionaryクラスには、コレクション内のすべてのキーを含むICollectionを取得するためのKeysプロパティが用意されています。この記事では、実際のコード例を使って、キーの一覧を取得して表示する方法をわかりやすく解説します。

Keysプロパティとは

OrderedDictionary.Keysプロパティは、OrderedDictionaryに格納されているすべてのキーを、挿入された順序どおりに含むICollectionオブジェクトを返します。取得したコレクションはCopyToメソッドを使って配列にコピーできるため、ループ処理などで扱いやすくなります。

サンプルコード1:数値のキーを表示する

まずは、数値を文字列としてキーに登録した基本的な例を見てみましょう。

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      dict.Add("7", "Seven");
      dict.Add("8", "Eight");

      ICollection col = dict.Keys;
      String[] strKeys = new String[dict.Count];
      col.CopyTo(strKeys, 0);

      Console.WriteLine("キーの一覧を表示します...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strKeys[i]);
      }
   }
}

実行結果

上記のコードを実行すると、次のような出力が得られます。

キーの一覧を表示します...
1
2
3
4
5
6
7
8

サンプルコード2:文字列のキーを表示する

続いて、キーに単語を使用した別の例です。処理の流れは先ほどと同じですが、キーの内容が異なります。

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("One", "John");
      dict.Add("Two", "Tim");
      dict.Add("Three", "Katie");
      dict.Add("Four", "Andy");
      dict.Add("Five", "Gary");
      dict.Add("Six", "Amy");

      ICollection col = dict.Keys;
      String[] strKeys = new String[dict.Count];
      col.CopyTo(strKeys, 0);

      Console.WriteLine("キーの一覧を表示します...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strKeys[i]);
      }
   }
}

実行結果

このコードを実行すると、以下のように登録順にキーが出力されます。

キーの一覧を表示します...
One
Two
Three
Four
Five
Six

処理のポイント

  • KeysプロパティOrderedDictionaryのすべてのキーをICollectionとして返します。
  • CopyToメソッド:取得したコレクションを配列へコピーし、インデックスアクセスを可能にします。
  • 挿入順の保持OrderedDictionaryは要素を追加した順序を保持するため、出力もその順序になります。

このように、OrderedDictionaryKeysプロパティとCopyToメソッドを組み合わせることで、辞書内のすべてのキーを簡単に配列として取り出し、柔軟に操作することができます。

  1. 【C#】Dictionaryからキーのリストを取得する方法

    C#では、Dictionary<TKey, TValue> に格納されたすべてのキーを、List<TKey> として簡単に取り出すことができます。この記事では、Keys プロパティを使ってキーの一覧をリスト化し、画面に表示するまでの手順をサンプルコード付きで解説します。 Dictionaryに要素を追加する まずは、辞書(Dictionary)に要素を設定しましょう。 Dictionary<int, string> d = new Dictionary<int, string>(); // 辞書の要素 d.Add(1, "One&q

  2. C#でキーに基づいてDictionary(HashMap相当)をソートする方法

    実は「HashMap」はJavaのクラスであり、C#には存在しません。C#においてHashMapに相当するのは、キーと値のペア(key-value pair)を格納するコレクションであるDictionaryです。本記事では、C#のDictionaryをキー順にソートする方法を、具体的なサンプルコードとともに解説します。1. Dictionaryの準備まずは、ソート対象となるDictionaryを作成します。ここでは、スポーツ名をキー、番号を値として登録します。Dictionary<string, int> d = new Dictionary<string, int>(