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

C#のSortedDictionary.Keysプロパティとは?使い方とサンプルコードを解説

C#におけるSortedDictionary.Keysプロパティは、SortedDictionary<TKey, TValue>に格納されているすべてのキーを含むコレクションを取得するために使用されます。取得できるのはKeyCollection型のコレクションで、foreachループなどを使って各キーを順番に取り出すことができます。

SortedDictionaryは内部でキーをソートされた状態で保持するため、Keysプロパティで取得したキーのコレクションも、必ず昇順に並んだ状態で返される点が特徴です。

構文

Keysプロパティの構文は以下のとおりです。

public System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection Keys { get; }

使用例1:キーの一覧を取得して表示する

まず、基本的な使用例を見てみましょう。以下のコードでは、SortedDictionaryに要素を追加した後、Keysプロパティを使ってすべてのキーを取得し、コンソールに表示しています。

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(1, "SUV");
      sortedDict.Add(2, "MUV");
      sortedDict.Add(3, "Utility Vehicle");
      sortedDict.Add(4, "AUV");
      sortedDict.Add(5, "Hatchback");
      sortedDict.Add(6, "Convertible");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedDictionary key-value pairs = "+sortedDict.Count);
      sortedDict.Add(7, "Seven");
      sortedDict.Add(8, "Eight");
      Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
      Console.WriteLine("Value in the SortedDictionary key-value pair key five = "+sortedDict[5]);
      sortedDict[5] = "Crossover";
      Console.WriteLine("Value in the SortedDictionary key-value pair key five (updated) = "+sortedDict[5]);
      SortedDictionary<int, string>.KeyCollection keyColl = sortedDict.Keys;
      Console.WriteLine("\nKeys...");
      foreach( int i in keyColl ){
         Console.WriteLine(i);
      }
   }
}

出力結果

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

SortedDictionary key-value pairs...
Key = 1, Value = SUV
Key = 2, Value = MUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = AUV
Key = 5, Value = Hatchback
Key = 6, Value = Convertible
Count of SortedDictionary key-value pairs = 6
SortedDictionary key-value pairs...UPDATED
Key = 1, Value = SUV
Key = 2, Value = MUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = AUV
Key = 5, Value = Hatchback
Key = 6, Value = Convertible
Key = 7, Value = Seven
Key = 8, Value = Eight
Count of SortedDictionary key-value pairs (UPDATED) = 8
Value in the SortedDictionary key-value pair key five = Hatchback
Value in the SortedDictionary key-value pair key five (updated) = Crossover
Keys...
1
2
3
4
5
6
7
8

この例では、要素の追加や値の更新を行った後、Keysプロパティから取得したKeyCollectionをforeachループで処理することで、キー「1」から「8」までが昇順に表示されていることが確認できます。

使用例2:ContainsKeyメソッドとの組み合わせ

続いて、別の例を見てみましょう。この例では、ContainsKeyメソッドで特定のキーの存在を確認した後、Keysプロパティですべてのキーを取得しています。

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("\nThe SortedDictionary has the key 200? = "+sortedDict.ContainsKey(200));
      SortedDictionary<int, string>.KeyCollection keyColl = sortedDict.Keys;
      Console.WriteLine("\nKeys...");
      foreach( int i in keyColl ){
         Console.WriteLine(i);
      }
   }
}

出力結果

実行すると、以下の出力が得られます。

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone
The SortedDictionary has the key 200? = True
Keys...
100
200
300
400
500
600

まとめ

SortedDictionary.Keysプロパティを使用すると、ディctionary内のすべてのキーをKeyCollectionとして簡単に取得できます。主なポイントは以下のとおりです。

  • 戻り値は読み取り専用のKeyCollection型で、キーのみを格納します。
  • SortedDictionaryの特性上、キーは常にソート済み(昇順)の状態で返されます。
  • foreachループと組み合わせることで、すべてのキーを簡潔に列挙できます。

キーの一覧が必要な場面、たとえば検索処理や一括表示などで、このプロパティは非常に便利です。ぜひ活用してみてください。

  1. 【C#】Console.KeyAvailableプロパティの使い方とサンプルコード

    Console.KeyAvailableプロパティとはC#のConsole.KeyAvailableプロパティは、標準入力ストリームにキー入力が利用可能かどうかを示す値を取得するためのプロパティです。戻り値はbool型で、キー入力があればtrue、なければfalseを返します。このプロパティは読み取り専用(getのみ)であり、Console.ReadKey()メソッドと組み合わせることで、処理をブロックすることなくキー入力の有無を確認しながらループ処理を実装できます。構文public static bool KeyAvailable { get; }使用例1:キー入力を検出して表示する以下は、

  2. Chromebookでファンクションキー(F1〜F12)を使う方法【ショートカット早見表つき】

    Chromebookユーザーの多くが最初に戸惑うのが、その独特なキーボード配置です。検索キーが搭載されている一方で、Caps Lockキーやファンクションキー(F1〜F12)の列など、従来のPCにはあった多くのキーが省略されています。Googleは大胆にも定番のファンクションキーを廃止しましたが、その分の機能性を犠牲にしたわけではありません。Chromebookでは、賢いキーの組み合わせによって、省略されたキーの機能にアクセスできるようになっています。ファンクションキー(F1〜F12)の入力方法ファンクションキーはさまざまなプラットフォームで広く使われており、Chromebookでもアプリやツ