C#のDictionary.Add()メソッド
C#のDictionary.Add()メソッドは、指定されたキーと値をディクショナリに追加するために使用されます。
構文
以下は構文です-
public void Add (TKey key, TValue val);
上記では、keyパラメータがキーですが、Valは要素の値です。
例
ここで、Dictionary.Add()メソッドを実装する例を見てみましょう-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
} 出力
これにより、次の出力が生成されます-
Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan
例
ここで、Dictionary.Add()メソッドを実装する別の例を見てみましょう-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
dict.Add("Six", "Anne");
dict.Add("Seven", "Katie");
Console.WriteLine("Count of elements (updated) = "+dict.Count);
Console.WriteLine("Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
} 出力
これにより、次の出力が生成されます-
Count of elements = 5 Count of elements (updated) = 7 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Key = Six, Value = Anne Key = Seven, Value = Katie
-
C#でのハッシュテーブルと辞書の操作
ハッシュテーブル ハッシュテーブルクラスは、キーのハッシュコードに基づいて編成されたキーと値のペアのコレクションを表します。キーを使用してコレクション内の要素にアクセスします。 Hashtableクラスで一般的に使用されるメソッドのいくつかは-です。 Sr.No。 メソッドと説明 1 public virtual void Add(object key、object value); 指定されたキーと値を持つ要素をハッシュテーブルに追加します。 2 public virtual void Clear(); ハッシュテーブルからすべての要素を削除しま
-
Pythonの辞書にキーと値のペアを追加する
Python辞書は、キーと値のペアの順序付けられていないコレクションです。このチュートリアルでは、定義済みの辞書に新しいキーと値のペアを追加する方法を説明します。以下は、使用できる2つのアプローチです。 新しいキーを添え字として割り当てる 新しいキーを添え字として使用し、それに値を割り当てることによって、辞書に新しい要素を追加します。 例 CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1} print(CountryCodeDict) CountryCodeDict[&quo