【C#】Dictionary使用汇总

1、排序

//字典按键值升序排序
dic = dic.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);    
//字典按键值降序排序                
dic = dic.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, o => o.Value);

2、遍历

//遍历Key和Value
for (int i = 0; i < dic.Count; i++)
    Console.WriteLine($"Key:{dic.Keys.ToArray()[i]},Value:{dic.Values.ToArray()[i]}");
foreach(KeyValuePair<int, string> kvp in dic)
    Console.WriteLine($"Key:{kvp.Key},Value:{kvp.Value}");

//遍历Key
foreach(var key in dic.Keys)
    Console.WriteLine($"Key:{key}");

//遍历Value
foreach(var value in dic.Values)
    Console.WriteLine($"Value:{value}");    

3、根据Key值取Value

//确定key在字典集中存在
string value = dic[1];
//不确定key是否存在字典集当中
value = dic.FirstOrDefault(d=>d.key == 1).Value;

4、根据Value值取Key

//lambada表达式
int key = dic.FirstOrDefault(d => d.Value == "李四").Key;
//linq to object
key = (from query in dic.AsEnumerable()
       where query.Value == "王五"
       select new 
       { 
               query.Key 
       }
       ).Select(d => d.Key).ToList().FirstOrDefault();

5、判断Key或Value是否存在

//判断Key是否存在
bool keyBool = false;
keyBool = dic.Keys.Contain(key);
keyBool = dic.ContainsKey(key);

//判断Value是否存在
bool valueBool = false;
valueBool = dic.Values.Contain(key);
valueBool = dic.ContainsValue(key);

6、移除元素

//移除单个元素
dic.Remove(key);
//移除所有
dic.Clear();

链接

/*******相与枕藉乎舟中,不知东方之既白*******/
原文地址:https://www.cnblogs.com/Mars-0603/p/15343634.html