Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Tim Corey
10 分 19 秒
C#の強力なデータ構造で、あまり活用されていないのが辞書です。 Dictionaryクラスは、System.Collections.Generic名前空間にある汎用コレクションです。 The Dictionary Data Structure in C# in 10 Minutes or Less" というビデオでは、Tim Corey が、C# アプリケーションで辞書を効果的に使用する方法について、簡潔で実用的なガイドを提供しています。 この記事では、ティムの説明と例を分解し、C#辞書の要点を簡単に把握できるようにすることを目的としています。
ティムはまず、C#における辞書の概念を紹介します。 彼はこれを、単語(キー)を調べてその定義(値)を見つける現実の辞書に例えています。 C#では、辞書はキーと値のペアのコレクションであり、各キーは一意であり、NULLにすることはできません。
C#で辞書はDictionary<TKey, TValue>構文を使用して宣言され、キーと値のペアを通じて効率的なデータの保存と取得を可能にします。 インスタンス化時にデフォルトの初期容量が設定され、要素が追加されると、辞書は動的に調整されます。
(0:28)で、ティムは基本的なコンソール・アプリケーションから始め、辞書の作成方法を実演します。 彼は以下のコードを使って、整数をキー、文字列を値とする辞書を初期化しています:
// Declare a dictionary with integer keys and string values
Dictionary<int, string> rookieOfTheYear = new Dictionary<int, string>();' Declare a dictionary with integer keys and string values
Dim rookieOfTheYear As New Dictionary(Of Integer, String)()' Declare a dictionary with integer keys and string values
Dim rookieOfTheYear As New Dictionary(Of Integer, String)()ここでstring)であることを指定します。 変数rookieOfTheYearは辞書インスタンスの名前です。 キータイプをstringに設定することで、文字列キーを使用することもできます。
Timは現在、(2:08)で辞書に要素を追加しています。 彼はキーと値のペアを追加するためにAddメソッドを使用する方法を示しています。
// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");' Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller")
rookieOfTheYear.Add(2001, "Jane Doe")
rookieOfTheYear.Add(2002, "Jane Doe")
rookieOfTheYear.Add(2003, "John Smith")' Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller")
rookieOfTheYear.Add(2001, "Jane Doe")
rookieOfTheYear.Add(2002, "Jane Doe")
rookieOfTheYear.Add(2003, "John Smith")この例では:
"Mike Miller"を追加します。
同様に、キー"John Smith"と関連しています。
また、値は繰り返し使用できますが、キーは一意でなければなりません。 重複するキーを追加しようとすると、例外が発生します:
rookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe") ' This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe") ' This will throw an exceptionこの例外は、キー2001が辞書にすでに存在しているために発生します。
価値検索を実演するために、ティムは(3:45)で次のコード行を使用する:
// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe' Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear(2002)) ' Outputs: Jane Doe' Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear(2002)) ' Outputs: Jane Doeここで2002に関連する値にアクセスします。 これは、キーに基づいて値を検索する非常に効率的な方法です。
C# Dictionaryを理解する
(4:29)にて、ティムは辞書内にキーが存在するかをContainsKeyメソッドを使用して確認する方法を論じています。
// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}' Check if a key exists before accessing its value
If rookieOfTheYear.ContainsKey(2002) Then
Console.WriteLine(rookieOfTheYear(2002))
End If' Check if a key exists before accessing its value
If rookieOfTheYear.ContainsKey(2002) Then
Console.WriteLine(rookieOfTheYear(2002))
End If上記の例では、2002が辞書に存在するかどうかを確認します。 もし存在する場合、対応する値("Jane Doe")が出力されます。
キーが存在しない場合、辞書は出力を返さず、存在しないキーへのアクセスによるエラーを防ぎます。
Timは、(5:33)で辞書の機能について説明し、文字列を文字列のリストにマッピングする辞書で、より複雑な例を作成します:
// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });' Declare a dictionary with string keys and List(Of String) as values
Dim wishList As New Dictionary(Of String, List(Of String))()
' Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", New List(Of String) From {"Xbox", "Tesla", "Pizza"})
wishList.Add("Billy Bob", New List(Of String) From {"PS5", "Ford", "Hoagie"})
wishList.Add("Mary Jane", New List(Of String) From {"House", "Car", "Sub"})' Declare a dictionary with string keys and List(Of String) as values
Dim wishList As New Dictionary(Of String, List(Of String))()
' Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", New List(Of String) From {"Xbox", "Tesla", "Pizza"})
wishList.Add("Billy Bob", New List(Of String) From {"PS5", "Ford", "Hoagie"})
wishList.Add("Mary Jane", New List(Of String) From {"House", "Car", "Sub"})こちら
キーは文字列です(例:"Tim Corey"、"Billy Bob"、"Mary Jane")。
値は文字列のリストで、各人のウィッシュリストを表します。
(7:24)にて、ティムはforeachループを使用して辞書を反復する方法を示しています。
// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}' Iterate over each key-value pair in the dictionary
For Each kvp In wishList
Dim key = kvp.Key
Dim value = kvp.Value
Console.WriteLine($"{key}'s wish list:")
' Iterate over each item in the list of values
For Each item In value
Console.WriteLine(vbTab & item)
Next
Next' Iterate over each key-value pair in the dictionary
For Each kvp In wishList
Dim key = kvp.Key
Dim value = kvp.Value
Console.WriteLine($"{key}'s wish list:")
' Iterate over each item in the list of values
For Each item In value
Console.WriteLine(vbTab & item)
Next
Nextこの例では:
wishList辞書内の各キーと値のペアを反復処理します。
keyはキーを指します(例:"ティム・コーリー")。
valueは、そのキーに関連する値のリストを指します。
内側のループは、リストの各項目を繰り返し、それを表示します。
これは、指定されたキーとそれに対応する指定された値で辞書要素に1つずつアクセスするループを使用して、すべての要素を印刷することができます。 ここに出力があります:
C# Dictionaryを理解する
Timはまた、(8:26)で、指定されたインデックスを明示的に使用して、辞書のより複雑な値にアクセスする方法を示しています:
// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox' Access the first item in the list of values for the specified key
Console.WriteLine(wishList("Tim Corey")(0)) ' Outputs: Xbox' Access the first item in the list of values for the specified key
Console.WriteLine(wishList("Tim Corey")(0)) ' Outputs: Xboxここで[0]はそのリストの最初のアイテムを取得します。
ティムは、辞書を理解することの重要性を強調し、(9:00)で締めくくります。 辞書は頻繁に使用されるものではないかもしれないが、ユニークなキーや効率的なルックアップを必要とするシナリオでは非常に有用である、と彼は指摘する。
辞書の作成: さまざまなデータ型で辞書を初期化する方法を理解します。
要素の追加:一意のキーの重要性と、重複キーの例外を処理する方法を学びます。
値へのアクセス: キーを使用して効率的に値を取得します。
キーの存在チェック: 値にアクセスする前にキーの存在をチェックすることで、エラーを防ぎます。
高度な使用法: 値としてリストを使用するなど、より複雑な辞書を実装します。
反復:ループを使用して、辞書内のすべての要素にアクセスし、表示します。
ティム・コーリーのビデオに従うことで、C#での辞書の使い方をマスターし、効率的なデータの検索と保存を必要とするシナリオのためのプログラミングツールキットを強化することができます。 Timのチャンネルで、C#に関するその他の有益なビデオをご覧ください。
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Join our newsletter, you’ll get exclusive access on article updates. We value your privacy