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

C#のStringDictionaryでキーのコレクションを取得する方法

C#のStringDictionaryでキーのコレクションを取得する方法

StringDictionaryからキーのコレクションを取得するには、Keysプロパティを使用します。このプロパティは、ディクショナリに格納されているすべてのキーをICollectionオブジェクトとして返します。

さらに、CopyToメソッドを組み合わせれば、取得したキーのコレクションを文字列配列(String[])にコピーでき、インデックスを指定して個々のキーにアクセスすることも可能です。

以下では、実際のサンプルコードと実行結果をもとに、具体的な手順を解説します。

例1:Keysプロパティでキーの一覧を取得する

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

public class Demo {
   public static void Main(){
      // 1つ目のStringDictionaryを作成し、要素を追加
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("U", "Electronics");
      strDict1.Add("V", "Toys");
      strDict1.Add("W", "Books");
      strDict1.Add("X", "Accessories");

      Console.WriteLine("StringDictionary1 elements...");
      foreach(DictionaryEntry d in strDict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      // 指定したキーが存在するかどうかを確認
      Console.WriteLine("Does StringDictionary1 has key G? " + strDict1.ContainsKey("G"));

      // 2つ目のStringDictionaryを作成し、要素を追加
      StringDictionary strDict2 = new StringDictionary();
      strDict2.Add("A", "John");
      strDict2.Add("B", "Andy");
      strDict2.Add("C", "Tim");
      strDict2.Add("D", "Ryan");
      strDict2.Add("E", "Kevin");
      strDict2.Add("F", "Katie");
      strDict2.Add("G", "Brad");

      Console.WriteLine("\nStringDictionary2 elements...");
      foreach(DictionaryEntry d in strDict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      // Keysプロパティでキーのコレクションを取得し、配列にコピー
      Console.WriteLine("\nCollection of keys (StringDictionary2)...");
      String[] keyArr = new String[strDict2.Count];
      strDict2.Keys.CopyTo(keyArr, 0);

      for (int i = 0; i < strDict2.Count; i++) {
         Console.WriteLine("Key " + (i+1) + " = " + keyArr[i]);
      }

      Console.WriteLine("\nIs Dictionary2 equal to Dictionary1? = " + strDict2.Equals(strDict1));
      Console.WriteLine("Does StringDictionary2 has key B? " + strDict2.ContainsKey("B"));
   }
}

実行結果

StringDictionary1 elements...
x Accessories
u Electronics
v Toys
w Books
Does StringDictionary1 has key G? False
StringDictionary2 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Collection of keys (StringDictionary2)...
Key 1 = a
Key 2 = b
Key 3 = c
Key 4 = d
Key 5 = e
Key 6 = f
Key 7 = g
Is Dictionary2 equal to Dictionary1? = False
Does StringDictionary2 has key B? True

コードのポイント

  • KeysプロパティstrDict2.Keysで、StringDictionaryに含まれるすべてのキーをICollectionとして取得できます。
  • CopyToメソッドstrDict2.Keys.CopyTo(keyArr, 0)により、キーのコレクションを配列keyArrの先頭(インデックス0)から順にコピーします。
  • ContainsKeyメソッド:指定したキーが存在すればTrue、存在しなければFalseを返します。
  • キーは小文字で格納される:StringDictionaryは大文字・小文字を区別せず、キーは内部的に小文字に変換されて保存されます。そのため、大文字の「U」や「X」で追加しても、出力では「u」「x」と表示されます。

例2:キーと値をセットで表示する

次の例では、取得したキー配列をインデックスとして利用し、対応する値もあわせて表示しています。

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

public class Demo {
   public static void Main(){
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("S", "Home Appliances");
      strDict1.Add("T", "Smart Wearable Tech");
      strDict1.Add("U", "Electronics");
      strDict1.Add("V", "Toys");
      strDict1.Add("W", "Books");
      strDict1.Add("X", "Accessories");

      Console.WriteLine("StringDictionary elements...");
      foreach(DictionaryEntry d in strDict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      // キーのコレクションを配列にコピーし、キーと値をペアで表示
      Console.WriteLine("\nCollection of keys and values...");
      String[] keyArr = new String[strDict1.Count];
      strDict1.Keys.CopyTo(keyArr, 0);

      for (int i = 0; i < strDict1.Count; i++) {
         Console.WriteLine("Key " + (i+1) + " = " + keyArr[i] + ", Value " + (i+1) + " = " + strDict1[keyArr[i]]);
      }

      Console.WriteLine("\nDoes StringDictionary has key B? " + strDict1.ContainsKey("B"));
   }
}

実行結果

StringDictionary elements...
x Accessories
s Home Appliances
t Smart Wearable Tech
u Electronics
v Toys
w Books
Collection of keys and values...
Key 1 = x, Value 1 = Accessories
Key 2 = s, Value 2 = Home Appliances
Key 3 = t, Value 3 = Smart Wearable Tech
Key 4 = u, Value 4 = Electronics
Key 5 = v, Value 5 = Toys
Key 6 = w, Value 6 = Books
Does StringDictionary has key B? False

まとめ

StringDictionaryのキーのコレクションを取得するにはKeysプロパティを使い、CopyToメソッドと組み合わせることでキーを配列として扱えます。これにより、ループ処理でキーと値を柔軟に操作できるようになります。なお、StringDictionaryは大文字・小文字を区別しないため、キーは小文字で格納される点にも注意してください。

  1. MongoDBコレクションの全キー(フィールド名)を取得する方法まとめ

    この記事は2019年1月18日にObjectRocket.com/blogで公開された内容をもとにしています。 MongoDB®のコレクションに含まれるすべてのキーを把握することは、スキーマの検証、フィールド名のタイプミスのデバッグ、設定すべきでないフィールドの発見など、さまざまな場面で役立ちます。本記事では、MongoDBコレクション内の全キー名を取得する複数の方法を、状況別にわかりやすく解説します。 まず検討したい:ODMやマネージドサービスの活用 ObjectRocketをはじめとする多くのMongoDB-as-a-Service事業者は、ユーザーインターフェース(UI)上で簡単にキーを

  2. MongoDBコレクション内の全キー名を取得する方法|MapReduce・Aggregation・シェルなど状況別に解説

    スキーマの検証、フィールド名のタイプミスのデバッグ、設定されるべきではないフィールドの発見などを行うには、まずMongoDBコレクション内にどのようなキーが存在するのかを把握しておく必要があります。多くのMongoDB-as-a-Service事業者は、UI上で手軽にこれを実現できる機能を提供しています(ObjectRocketもそのひとつです)。また、経験豊富なMongoDBユーザーの多くは、JavaScript向けのMongooseやPython向けのMongoengineといったオブジェクトドキュメントマッパー(ODM)を導入しています。ODMを使えば、アプリケーション向けの一貫性のある