ディクショナリとは何ですか?
メニューを表示するにはスワイプしてください
配列では、インデックス(arrayName[index])を使ってデータにアクセスします。配列内の各値(要素)には一意のインデックスが割り当てられており、そのインデックスを使用して値にアクセスします。したがって、配列はインデックス-値構造を持つと言えます。
これに似た構造として、ディクショナリがあります。ディクショナリでは、キー-値のペアが使用されます。インデックスは常に整数ですが、キーは任意の基本データ型を使用でき、一般的にはstringがよく使われます。
次の図は、さまざまな果物の数を格納するディクショナリの例を示しています。
ディクショナリの作成
ディクショナリは、次の構文で宣言できます:
IDictionary<keyDataType, valueDataType> dictionaryName = new Dictionary<keyDataType, valueDataType>();
ここで keyDataType はキーのデータ型を表し、valueDataType は値のデータ型を表します。dictionaryName はディクショナリの名前です。
暗黙的な宣言も有効です:
var dictionaryName = new Dictionary<keyDataType, valueDataType>();
データの追加
Add メソッドを使用してディクショナリに要素を追加できます:
dictionaryName.Add(keyName, value);
データの取得
キーを使ってディクショナリ内のデータにアクセスできます:
dictionaryName[keyName]
次の例は、これら3つすべてを示しています。
index.cs
12345678910111213141516171819202122using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { var student = new Dictionary<string, string>(); student.Add("name", "Noah"); student.Add("country", "Netherlands"); student.Add("subject", "Computer Science"); Console.WriteLine(student["name"]); Console.WriteLine(student["country"]); Console.WriteLine(student["subject"]); } } }
ディクショナリ内の各キーは一意である必要があります。すでに存在するキーを追加しようとすると、コンパイラはエラーを表示します。
ディクショナリにおいて、Count 属性は格納されているキーと値のペアの数を示します。Remove メソッドはキーを受け取り、そのキーと値のペアをディクショナリから削除します。Clear メソッドはディクショナリ内のすべてのキーと値のペアを削除します。以下のコードを読み、Count、Remove、Clear の使い方を理解することは良いコードリーディングの練習になります。
index.cs
1234567891011121314151617181920212223242526using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { var numbers = new Dictionary<int, string>(); numbers.Add(0, "Zero"); numbers.Add(1, "One"); numbers.Add(2, "Two"); numbers.Add(3, "Three"); numbers.Add(4, "Four"); numbers.Add(5, "Five"); Console.WriteLine(numbers.Count); // Output: 6 numbers.Remove(3); Console.WriteLine(numbers.Count); // Output: 5 numbers.Clear(); Console.WriteLine(numbers.Count); // Output: 0 } } }
1. ディクショナリを使用するためにインポートする必要があるモジュールはどれですか?
2. ディクショナリを作成する正しい構文はどれですか?
3. 次のコードの出力は何ですか?
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください