C# Dictionary用法彙總(定義、遍歷、排序)
阿新 • • 發佈:2018-12-26
1、Dictionary定義
Dictionary<string, double> dic = new Dictionary<string, double>();
dic.Add("語文", 98.5);
dic["數學"] = 97;
Dictionary<string, double> dic
= new Dictionary<string, double>() { {"語文",95},{"數學",98.5} };
2、通過KeyValuePair遍歷元素
3、Foreach遍歷字典
Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
foreach (int key in keyCol)
{
Console.WriteLine("Key = {0}", key);
} 4、For遍歷字典
for (int i = 0; i < dic.Count; i++) { KeyValuePair<string, double> kv = dic.ElementAt(i); Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value); } 5、僅遍歷 值 Key屬性
Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
foreach (int key in keyCol)
{
Console.WriteLine("Key = {0}", key);
}
6、僅遍歷值 Valus屬性
Dictionary<int, string>.ValueCollection valueCol = dic.Values;
foreach (string value in valueCol)
{
Console.WriteLine("Value = {0}", value);
} 7、通過Remove方法移除指定的鍵值 if (dic.ContainsKey("語文")) { Console.WriteLine("移除鍵:Key:{0},Value:{1}", "語文", dic["語文"]); dic.Remove("語文"); } else { Console.WriteLine("不存在 Key : 1"); } 8、字典排序 dic = dic .OrderByDescending(r => r.Value).ToDictionary(r => r.Key, r => r.Value);
foreach(KeyValuePair<int,string> kv in dic) { Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value); }
Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
foreach (int key in keyCol)
{
Console.WriteLine("Key = {0}", key);
} 4、For遍歷字典
for (int i = 0; i < dic.Count; i++) { KeyValuePair<string, double> kv = dic.ElementAt(i); Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value); } 5、僅遍歷
Dictionary<int, string>.ValueCollection valueCol = dic.Values;
foreach (string value in valueCol)
{
Console.WriteLine("Value = {0}", value);
} 7、通過Remove方法移除指定的鍵值 if (dic.ContainsKey("語文")) { Console.WriteLine("移除鍵:Key:{0},Value:{1}", "語文", dic["語文"]); dic.Remove("語文"); } else { Console.WriteLine("不存在 Key : 1"); } 8、字典排序 dic = dic .OrderByDescending(r => r.Value).ToDictionary(r => r.Key, r => r.Value);