• 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]");
        }
    }
      
    

      

  • 相关阅读:
    分布式缓存技术PK:选择Redis还是Memcached?
    Redis实战:如何构建类微博的亿级社交平台
    Redis内存使用优化与存储
    微信小程序 Image 图片实现宽度100%,高度自适应
    小程序跳转、请求、带参数请求小例子
    微信小程序 全局变量
    免费ftp服务器FileZilla Server配置
    分享一次在Windows Server2012 R2中安装SQL Server2008
    C# litJson 使用方法
    HttpHandler和ashx要实现IRequiresSessionState接口才能访问Session信息(转载)
  • 原文地址:https://www.cnblogs.com/soulsjie/p/16422671.html
Copyright © 2020-2023  润新知