s
o
u
l
s
j
i
e

C#字典Dictionary的使用

命名空间:System.Collections.Generic;
//创建字典
Dictionary<int, string> nameDic = new Dictionary<int, string>();

//1.Add(TKey key, TValue value)-往字典中追加元素
nameDic.Add(1, "张三");
nameDic.Add(2, "李四");
nameDic.Add(3, "王五");
Console.WriteLine("nameDic包含:" + nameDic.Count + "个元素");

//2.Add时不允许往字典中添加具有重复键的元素
//nameDic.Add(3, "老六"); //报错:System.ArgumentException已添加了具有相同键的项

//3.使用Clear()清空字典的内容
nameDic.Clear();
Console.WriteLine("nameDic.Clear()后包含:" + nameDic.Count + "个元素");

//4.ContainsKey(TKey key) 使用键进行字典检索
nameDic.Add(6, "test");
if (nameDic.ContainsKey(6))
{
    Console.WriteLine("nameDic中包含:键为6的元素");
}

//5.ContainsValue(TValue value)  使用值进行字典检索
nameDic.Add(7, "test");
if (nameDic.ContainsValue("test"))
{
    Console.WriteLine("nameDic中包含:值为test的元素");
}

//6.GetEnumerator() 返回字典遍历的枚举数
var lp = nameDic.GetEnumerator();
while (lp.MoveNext())//返回遍历下一个枚举数
{
    var dic = lp.Current;//当前字典元素
    Console.WriteLine($"Key[{dic.Key}]-Value[{dic.Value}]");
}
lp.Dispose();//释放资源

//7.bool Remove(TKey key) 移除指定键的元素
if (nameDic.Remove(7))
{
    Console.WriteLine($"Key[7]-成功移除");
}

//8.bool TryGetValue(TKey key, out TValue value) 获取指定key的值
string valueOfKey = "";
if (nameDic.TryGetValue(6, out valueOfKey))
{
    Console.WriteLine($"Key[6]-的value是{valueOfKey}");
}

//9.根据Key获取字典value值 ps:查找字典nameDic中key=6 和Key=7的值
nameDic.Add(7, "test");
Console.WriteLine(nameDic[6]);
Console.WriteLine(nameDic[7]);

//10.根据value值获取key ps:查找"test"在字典nameDic中的key值
foreach (var item in nameDic)
{
    if (item.Value == "test")
    {
        Console.WriteLine($"Key[{item.Key}]-的value是[test]");
    }
}
  

  

posted @ 2022-06-29 11:26  soulsjie  阅读(372)  评论(0编辑  收藏  举报
你累吗?累就对了,当你觉得累时证明你在走上坡路!-----NotFoundObject - 2016-12-14 08:43