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遍历 字典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
遍历字典
6、仅遍历值 Valus属性
Dictionary<int, string>.ValueCollection valueCol = dic.Values;
foreach (string value in valueCol)
{
Console.WriteLine("Value = {0}", value);
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);
}
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);