C# Dictionary

目录

Dictionary的本质

申明

增删查改

遍历

练习


Dictionary的本质

可以将Dictionary理解为 拥有泛型的Hashtable

它也是基于键的哈希代码组织起来的 键/值对

键值对类型从Hashtable的object变为了可以自己制定的泛型

申明

需要引用命名空间 using System.Collections.Generic

Dictionary<int, string> dictionary = new Dictionary<int, string>();

增删查改

注意:不能出现相同键

dictionary.Add(1, "123");

dictionary.Add(2, "222");

dictionary.Add(3, "222");

//dictionary.Add(3, "123");

1.只能通过键去删除

删除不存在键 没反应

dictionary.Remove(1);

dictionary.Remove(4);

2.清空

dictionary.Clear();

1.通过键查看值 找不到直接报错

Console.WriteLine(dictionary[2]);

Console.WriteLine(dictionary[1]);

2.查看是否存在

根据键检测

if( dictionary.ContainsKey(4) )

{

Console.WriteLine("存在键为1的键值对");

}

根据值检测

if (dictionary.ContainsValue("1234"))

{

Console.WriteLine("存在值为123的键值对");

}

Console.WriteLine(dictionary[1]);

dictionary[1] = "555";

Console.WriteLine(dictionary[1]);

遍历

用foreach遍历

Console.WriteLine(dictionary.Count);

1.遍历所有键

foreach (int item in dictionary.Keys)

{

Console.WriteLine(item);

Console.WriteLine(dictionary[item]);

}

2.遍历所有值

foreach (string item in dictionary.Values)

{

Console.WriteLine(item);

}

3.键值对一起遍历

foreach (KeyValuePair<int,string> item in dictionary)

{

Console.WriteLine("键:" + item.Key + "值:" + item.Value);

}

练习


cs 复制代码
main
{
Dictionary<char , int> dir = new Dictionary<char, int>();
Console.WriteLine("请输入字母");
string a= Console.ReadLine(); 
for (int i = 0; i < a.Length; i++)
{
    if (dir.ContainsKey(a[i]))  //这里的a[i]直接获取String里面的char字符 
    {                           //因为String本质就是Char[] 类型
        dir[a[i]]++;
    }
    else
    dir.Add (a[i], 1);
}
foreach (char c in dir.Keys)
{
    Console.WriteLine(c+"  " + dir[c] +"次");
}

}
cs 复制代码
class Program
{
    public   static void Main()
    {
        string[] h = new string[] {"一","二","三","四","五","六","七","八","九","十"};
        Dictionary<int,String> dic = new Dictionary<int,String>();
        for (int i = 1 ,j=0; i < 10; i++)
        {
            dic.Add(i, h[j]);
            j++;
        }
        Console.WriteLine("输入三个数");
       string temp= Console.ReadLine();
        
        int [] b = new int[temp.Length];
        for (int i = 0; i < temp .Length; i++)
        {
            b[i]=temp[i]-'0';
        }

        for (int i = 0; i < b.Length; i++)
        {
            Console.WriteLine(dic[b[i]]);
        }
    }
    
}
相关推荐
天涯路s2 分钟前
qt怎么自定义日志
开发语言·qt
Evand J7 分钟前
【自适应IMM】MATLAB编写的创新多模型,基于CA/CT双模型和观测自适应。二维平面目标位置估计,带误差统计特性输出,附代码下载链接
开发语言·matlab·ekf·imm·交互式多模型
我命由我1234510 分钟前
微信小程序 - scroll-view 的一些要点(scroll-view 需要设置滚动方向、scroll-view 需要设置高度)
开发语言·前端·javascript·微信小程序·小程序·前端框架·js
橙序员小站10 分钟前
Java 接入 Pinecone 搭建知识库踩坑实记
java·后端
7哥♡ۣۖᝰꫛꫀꪝۣℋ11 分钟前
Spring IoC&DI
java·开发语言·mysql
wadesir15 分钟前
Go语言反射之结构体的深比较(详解reflect.DeepEqual在结构体比较中的应用)
开发语言·后端·golang
即将进化成人机20 分钟前
springboot项目创建方式
java·spring boot·后端
c#上位机28 分钟前
halcon计算区域骨架
图像处理·人工智能·计算机视觉·c#·halcon
教练、我想打篮球28 分钟前
117 javaweb servlet+jsp 项目中修改了 数据库连接配置, 却怎么都不生效
java·servlet·jdbc·jsp