如何:使用集合初始設定式來初始化字典 (C# 程式設計手冊)
Dictionary<TKey,TValue> 包含索引鍵/值組的集合。 其 Add 方法採用兩個參數,其中之一供索引鍵之用,而另一個則供值之用。 若要初始化 Dictionary<TKey,TValue> 或任何其 Add
方法採用多個參數的所有集合,其中一個方式是將每個參數集以大括弧括住,如下列範例所示。 另一個選項是使用索引子初始設定式,也會顯示在下列範例中。
注意
這兩種初始化集合的方式之間的主要差別在於:在有重複索引鍵的情況下,例如:
{ 111, new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } },
{ 111, new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } },
Add 方法會擲回 ArgumentException:'An item with the same key has already been added. Key: 111'
,而範例的第二個部分 (公用讀取/寫入索引器方法) 會以相同的索引鍵悄悄地覆寫已經存在的項目。
提示
您可以使用 AI 協助 ,使用 GitHub Copilot初始化字典。
範例
在下列程式碼範例中,Dictionary<TKey,TValue> 會使用類型 StudentName
的執行個體進行初始化。 第一個初始化使用 Add
方法和兩個引數。 編譯器會針對每組 Add
索引鍵和 int
值產生 StudentName
呼叫。 第二個使用 Dictionary
類別的公用讀取/寫入索引子方法:
public class HowToDictionaryInitializer
{
class StudentName
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int ID { get; set; }
}
public static void Main()
{
var students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } },
{ 112, new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } },
{ 113, new StudentName { FirstName="Andy", LastName="Ruth", ID=198 } }
};
foreach(var index in Enumerable.Range(111, 3))
{
Console.WriteLine($"Student {index} is {students[index].FirstName} {students[index].LastName}");
}
Console.WriteLine();
var students2 = new Dictionary<int, StudentName>()
{
[111] = new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 },
[112] = new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } ,
[113] = new StudentName { FirstName="Andy", LastName="Ruth", ID=198 }
};
foreach (var index in Enumerable.Range(111, 3))
{
Console.WriteLine($"Student {index} is {students2[index].FirstName} {students2[index].LastName}");
}
}
}
請注意,在第一個宣告中,該集合的每個項目中都有兩組大括弧。 最內層括號會括住 StudentName
的物件初始設定式,最外層括號會括住要新增至 students
Dictionary<TKey,TValue> 的機碼值組。 最後,會以括號括住目錄的整個集合初始設定式。 在第二個初始化中,指派左側是索引鍵,右側是其值,並使用 StudentName
的物件初始設定式。
使用 GitHub Copilot 初始化字典
您可以在 IDE 中使用 GitHub Copilot 來產生 C# 程式代碼,以使用集合初始化運算式初始化字典。 您可以自訂提示,來根據您的需求新增具體細節。
下列文字顯示 Copilot Chat 的範例提示:
Generate C# code to initialize Dictionary<int, Employee> using key-value pairs within the collection initializer. The employee class is a record class with two properties: Name and Age.
GitHub Copilot 是由 AI 所提供,因此可能會有驚喜和錯誤。 如需詳細資訊,請參閱 Copilot 常見問題。
深入瞭解在 Visual Studio 中的 GitHub Copilot 和在 VS Code 中的 GitHub Copilot。