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

C#のListDictionaryに指定したキーと値を追加する方法

C#のListDictionaryに指定したキーと値を追加するには、Add()メソッドを使用します。この記事では、具体的なコード例とその実行結果をもとに、使い方をわかりやすく解説します。

ListDictionaryとは

ListDictionaryは、System.Collections.Specialized名前空間に属するコレクションクラスで、キーと値のペアを単一リンクリストとして格納します。要素数が少ない場合(目安として10項目程度まで)に高いパフォーマンスを発揮するため、小規模なデータを扱う際に適しています。

キーと値を追加する基本的な例

以下のコードでは、Add()メソッドを使って文字列のキーと値をListDictionaryに追加し、IDictionaryEnumeratorを使ってすべてのキーと値のペアを表示しています。

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

public class Demo {
   public static void Main(){
      ListDictionary dict = new ListDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");

      Console.WriteLine("ListDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
   }
}

実行結果

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

ListDictionary key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five

すべてのキーを取得して表示する例

次に、別の例を見てみましょう。ここでは整数値を値として10件追加し、Keysプロパティで全キーを取得して表示します。

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

public class Demo {
   public static void Main(){
      ListDictionary listDict = new ListDictionary();
      listDict.Add("1", 100);
      listDict.Add("2", 200);
      listDict.Add("3", 300);
      listDict.Add("4", 400);
      listDict.Add("5", 500);
      listDict.Add("6", 600);
      listDict.Add("7", 700);
      listDict.Add("8", 800);
      listDict.Add("9", 900);
      listDict.Add("10", 1000);

      ICollection col = listDict.Keys;
      Console.WriteLine("Display all the keys...");
      foreach(String s in col){
         Console.WriteLine(s);
      }
   }
}

実行結果

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

Display all the keys...
1
2
3
4
5
6
7
8
9
10

まとめ

ListDictionaryへの要素追加は、Add(キー, 値)メソッドを呼び出すだけで簡単に行えます。追加した要素は、IDictionaryEnumeratorによる列挙やKeysプロパティを使って柔軟に参照できます。ただし、大量のデータを扱う場合にはHashtableDictionary<TKey, TValue>の方が検索性能に優れているため、データ規模に応じて適切なコレクションを選択することが重要です。

  1. C#のSortedListで指定したキーに関連付けられた値を取得・設定する方法

    C#のSortedListクラスでは、インデクサ(this[])を使うことで、指定したキーに関連付けられた値を簡単に取得したり、上書き設定したりすることができます。基本的な使い方list[キー] の形式でアクセスすると、そのキーに対応する値が返されます。同じ構文で値を代入すると、既存のキーの値を更新できます。サンプルコード以下の例では、SortedListに複数のキーと値を追加し、キー「E」に関連付けられた値を取得した後、新しい値で更新しています。using System; using System.Collections; public class Demo { public sta

  2. C#のListDictionaryで指定したキーに関連付けられた値を取得・設定する方法

    C#のListDictionaryでは、インデクサー(Itemプロパティ)を使うことで、指定したキーに関連付けられた値を簡単に取得したり、新しい値に更新したりできます。ListDictionaryはSystem.Collections.Specialized名前空間に属するコレクションで、要素数が少ない場合(目安として10項目程度まで)に高いパフォーマンスを発揮する特徴があります。以下のコード例では、キー「C」に関連付けられた値の取得と更新の両方を確認できます。例1:キーに関連付けられた値を取得するusing System; using System.Collections; using Sy