C#中字典Dictionary的用法
1.创建Dictionary
Dictionary<int, string> dic = new Dictionary<int, string>();
2.Dictionary添加元素
//dic.Add(Key,Value);
dic.Add(1, "张三");
dic.Add(2, "李四");
dic.Add(3, "王五");
dic.Add(4, "李六");
dic.Add(5, "赵七");
dic[6] = "斗帝";//public TValue this[TKey key] { get; set; }
3.遍历
//遍历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}");
4.根据Key值取Value
//确定key在字典集中存在
string value = dic[1];
//不确定key是否存在字典集当中
value = dic.FirstOrDefault(d=>d.key == 1).Value;
5.根据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();
6.判断Key是否存在
bool keyBool = false;
keyBool = dic.Keys.Contain(key);
keyBool = dic.ContainsKey(key);
7.判断Value是否存在
bool valueBool = false;
valueBool = dic.Values.Contain(key);
valueBool = dic.ContainsValue(key);
8.移除元素
//移除单个元素
dic.Remove(key);
//移除所有
dic.Clear();