Dictionary<TKey, TValue>
類別,其中 TKey 表示鍵(Key)的類型,TValue 表示值(Value)的類型。 Dictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, string> dict2 = new Dictionary<int, string>{
[1] = "C#",
[2] = "C++"
};
Console.WriteLine( "dict總長度:" + dict.Count );
// dict總長度:0
dict.Add(1,"C#");
dict.Add(2,"C++");
Console.WriteLine(dict[1]); // C#
Console.WriteLine(dict[2]); // C++
dict[2] = "Python";
Console.WriteLine(dict[2]); // Python
if(dict.ContainsKey(1)){
Console.WriteLine("Key:{0},Value:{1}","1", dict[1]);
}
if(dict.ContainsValue("C#")){
Console.WriteLine("C# in dict1");
}
通過KeyValuePair遍歷
foreach(KeyValuePair<int,string>item in dict)
{
Console.WriteLine("Key = {0}, Value = {1}"
,item.Key, item.Value);
}
//Key = 1, Value = C#
//Key = 2, Value = Python
取得所有的 Keys
Dictionary<int, string>.KeyCollection keys = dict.Keys;
foreach (int key in keys)
{
Console.WriteLine(key);
}
取得所有的 Values
Dictionary<int, string>.ValueCollection values = dict.Values;
foreach (string v in values)
{ Console.WriteLine(v); }
dict.Remove(1);
if(!dict.ContainsKey(1)){
Console.WriteLine("duct[1] not in dict1");
// duct[1] not in dict1
}
dict.Clear();
Console.WriteLine( "dict總長度:" + dict.Count );
// dict總長度:0
* 程式範例:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>();
Console.WriteLine( "dict總長度:" + dict.Count );
Console.WriteLine("==========");
dict.Add(1,"C#");
dict.Add(2,"C++");
Console.WriteLine(dict[1]);
Console.WriteLine(dict[2]);
foreach (var items in dict)
{
Console.WriteLine(items.Key + ": " + items.Value);
}
Console.WriteLine("==========");
if(dict.ContainsKey(1)){
Console.WriteLine("Key:{0},Value:{1}","1", dict[1]);
}
Console.WriteLine("==========");
if(dict.ContainsValue("C#")){
Console.WriteLine("C# in dict1");
}
Console.WriteLine("==========");
string value = dict[1];
Console.WriteLine(value); // C#
Console.WriteLine("==========");
dict[2] = "Python";
Console.WriteLine(dict[2]); // Python
Console.WriteLine("==========");
foreach(KeyValuePair<int,string>item in dict)
{
Console.WriteLine("Key = {0}, Value = {1}",item.Key, item.Value);
}
Console.WriteLine("==========");
Dictionary<int, string>.KeyCollection keys = dict.Keys;
foreach (int key in keys)
{
Console.WriteLine(key);
}
Console.WriteLine("==========");
Dictionary<int, string>.ValueCollection values = dict.Values;
foreach (string v in values)
{
Console.WriteLine(v);
}
Console.WriteLine("==========");
}
}
}
```
* 輸出結果
```
dict總長度:0
==========
C#
C++
1: C#
2: C++
==========
Key:1,Value:C#
==========
C# in dict1
==========
C#
==========
Python
==========
Key = 1, Value = C#
Key = 2, Value = Python
==========
1
2
==========
C#
Python
==========
```
期望挑戰30天持續更新成功 ~ DAY9