C#字典教程展示了如何在C#中使用字典集合。
C#字典
字典,也称为关联数组,是唯一键的集合和值的集合,其中每个键与一个值相关联。检索和添加值非常快。字典占用更多内存,因为每个值都有一个键。
C#字典初始化器
C#字典可以用文字符号来初始化。这些元素被添加到赋值的右侧,在{}
方括号内。
var domains = new Dictionary<string, string> { {"sk", "Slovakia"}, {"ru", "Russia"}, {"de", "Germany"}, {"no", "Norway"} }; Console.WriteLine(domains["sk"]); var days = new Dictionary<string, string> { ["mo"] = "Monday", ["tu"] = "Tuesday", ["we"] = "Wednesday", ["th"] = "Thursday", ["fr"] = "Friday", ["sa"] = "Saturday", ["su"] = "Sunday" }; Console.WriteLine(days["fr"]);
在示例中,我们使用文字符号创建了两个字典。
var domains = new Dictionary<string, string> { {"sk", "Slovakia"}, {"ru", "Russia"}, {"de", "Germany"}, {"no", "Norway"} };
创建了一个新字典。在尖括号>
之间,我们指定键和值的数据类型。新的键/值元素对写入嵌套的{}
括号内;每对由逗号字符分隔。例如,“sk”
键指的是“Slovakia”
值。
Console.WriteLine(domains["sk"]);
要获取值,我们指定字典名称后跟方括号[]
。在括号之间,我们指定键名。
var days = new Dictionary<string, string> { ["mo"] = "Monday", ["tu"] = "Tuesday", ["we"] = "Wednesday", ["th"] = "Thursday", ["fr"] = "Friday", ["sa"] = "Saturday", ["su"] = "Sunday" };
这是一个替代的C#字典初始化器。使用字典访问符号将值分配给键。
$ dotnet run Slovakia Friday
C#字典计数元素
通过Count
属性,我们可以得到字典中的键数。
var domains = new Dictionary<string, string> { {"sk", "Slovakia"}, {"ru", "Russia"}, {"de", "Germany"}, {"no", "Norway"} }; domains.Add("pl", "Poland"); Console.WriteLine($"There are {domains.Count} items in the dictionary");
该示例计算字典中的项目数。
Console.WriteLine($"There are {domains.Count} items in the dictionary");
这里我们打印字典中的项目数。
$ dotnet run There are 5 items in the dictionary
C#字典添加、删除元素
创建字典后,可以在字典中添加或删除新元素。
var users = new Dictionary<string, int>() { { "John Doe", 41 }, { "Jane Doe", 38 }, { "Lucy Brown", 29 }, }; users["Paul Brown"] = 33; users.Add("Thomas Pattison", 34); Console.WriteLine(string.Join(", ", users)); users.Remove("Jane Doe"); Console.WriteLine(string.Join(", ", users)); users.Clear(); if (users.Count == 0) { Console.WriteLine("The users dictionary is empty"); }
该示例创建了一个新字典并使用多个内置方法对其进行了修改。
var users = new Dictionary<string, int>() { { "John Doe", 41 }, { "Jane Doe", 38 }, { "Lucy Brown", 29 }, };
创建了一个新字典。用户名是键,用户年龄是值。
users["Paul Brown"] = 33; users.Add("Thomas Pattison", 34);
我们使用字典访问符号和Add
方法将两个新对添加到字典中。
Console.WriteLine(string.Join(", ", users));
我们使用字符串Join
方法一次性显示所有元素。
users.Remove("Jane Doe");
使用Remove
方法删除一对。参数为字典键。
users.Clear();
使用Clear
方法清除字典。
$ dotnet run [John Doe, 41], [Jane Doe, 38], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34] [John Doe, 41], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34] The users dictionary is empty
C#DictionaryContainsKey和ContainsValue方法
ContainsKey
方法判断字典是否包含指定的键,ContainsValue
方法判断字典是否包含指定的值。
var domains = new Dictionary<string, string> { {"sk", "Slovakia"}, {"ru", "Russia"}, {"de", "Germany"}, {"no", "Norway"} }; var key = "sk"; if (domains.ContainsKey(key)) { Console.WriteLine($"The {key} key is in the dictionary"); } else { Console.WriteLine($"The {key} key is in not the dictionary"); } var value = "Slovakia"; if (domains.ContainsValue(value)) { Console.WriteLine($"The {value} value is in the dictionary"); } else { Console.WriteLine($"The {value} value is in not the dictionary"); }
在示例中,我们检查字典中是否存在"sk"
键和"Slovakia"
值。
$ dotnet run The sk key is in the dictionary The Slovakia value is in the dictionary
C#遍历字典
有几种遍历C#字典的方法。
var domains = new Dictionary<string, string> { {"sk", "Slovakia"}, {"ru", "Russia"}, {"de", "Germany"}, {"no", "Norway"} }; foreach (var (key, value) in domains) { Console.WriteLine($"{key}: {value}"); } Console.WriteLine("**************************************"); foreach (var kvp in domains) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } Console.WriteLine("**************************************"); // oldschool foreach (KeyValuePair<string, string> entry in domains) { Console.WriteLine($"{entry.Key}: {entry.Value}"); }
该示例使用foreach
遍历字典。
foreach (var (key, value) in domains) { Console.WriteLine($"{key}: {value}"); }
在这个foreach循环中,我们成对地遍历字典。每对都分解为其键和值。
foreach (var kvp in domains) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); }
在这种情况下,我们通过它们的Key
和Value
属性访问键和值。
// oldschool foreach (KeyValuePair<string, string> entry in domains) { Console.WriteLine($"{entry.Key}: {entry.Value}"); }
最后,这是一种使用KeyValuePair
成对遍历字典的旧方法。
$ dotnet run sk: Slovakia ru: Russia de: Germany no: Norway ************************************** sk: Slovakia ru: Russia de: Germany no: Norway ************************************** sk: Slovakia ru: Russia de: Germany no: Norway
C#允许分别循环键和值。
var domains = new Dictionary<string, string> { {"sk", "Slovakia"}, {"ru", "Russia"}, {"de", "Germany"}, {"no", "Norway"} }; Console.WriteLine("Keys:"); foreach (var val in domains.Keys) { Console.WriteLine(val); } Console.WriteLine("\nValues:"); foreach (var val in domains.Values) { Console.WriteLine(val); }
该示例在两个foreach
循环中打印字典的所有键和所有值。
foreach (var val in domains.Keys) { Console.WriteLine(val); }
我们使用Keys
属性获取所有键。
foreach (var val in domains.Values) { Console.WriteLine(val); }
我们使用Values
属性来获取所有值。
$ dotnet run Keys: sk ru de no Values: Slovakia Russia Germany Norway
C#字典排序
我们可以使用LINQ对字典进行排序。
var users = new Dictionary<string, int>() { { "John", 41 }, { "Jane", 38 }, { "Lucy", 29 }, { "Paul", 24 } }; var sortedUsersByValue = users.OrderBy(user => user.Value); foreach (var user in sortedUsersByValue) { Console.WriteLine($"{user.Key} is {user.Value} years old"); }
该示例按用户年龄对字典进行排序。
var sortedUsersByValue = users.OrderBy(user => user.Value);
OrderBy
方法用于按条目的值对条目进行排序。
$ dotnet run Paul is 24 years old Lucy is 29 years old Jane is 38 years old John is 41 years old
C#排序字典
SortedDictionary
表示按键排序的键/值对的集合。
var sortedUsers = new SortedDictionary<string, int>() { { "John", 41 }, { "Jane", 38 }, { "Lucy", 29 }, { "Paul", 24 } }; foreach (var user in sortedUsers) { Console.WriteLine($"{user.Key} is {user.Value} years old"); }
该示例演示了SortedDictionary
的用法。
$ dotnet run Jane is 38 years old John is 41 years old Lucy is 29 years old Paul is 24 years old
C#列表字典
在下面的例子中,我们有一个列表字典。
var data = new Dictionary<int, List<int>>(); var vals1 = new List<int> { 1, 1, 1, 1, 1 }; var vals2 = new List<int> { 3, 3, 3, 3, 3 }; var vals3 = new List<int> { 5, 5, 5, 5, 5 }; data.Add(1, vals1); data.Add(2, vals2); data.Add(3, vals3); var TotalSum = 0; foreach (var (key, e) in data) { var _sum = e.Sum(); TotalSum += _sum; Console.WriteLine($"The sum of nested list is: {_sum}"); } Console.WriteLine($"The total sum is: {TotalSum}");
我们将三个整数列表添加到字典中。我们计算每个嵌套列表的总和以及最终的总和。
$ dotnet run The sum of nested list is: 5 The sum of nested list is: 15 The sum of nested list is: 25 The total sum is: 45
在本文中,我们使用了C#字典集合。
列出所有C#教程。