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(dictionary2);

Console.WriteLine(dictionary1);

2.查看是否存在

根据键检测

if( dictionary.ContainsKey(4) )

{

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

}

根据值检测

if (dictionary.ContainsValue("1234"))

{

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

}

Console.WriteLine(dictionary1);

dictionary1 = "555";

Console.WriteLine(dictionary1);

遍历

用foreach遍历

Console.WriteLine(dictionary.Count);

1.遍历所有键

foreach (int item in dictionary.Keys)

{

Console.WriteLine(item);

Console.WriteLine(dictionaryitem);

}

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]]);
        }
    }
    
}
相关推荐
Raas10038 分钟前
AI网关和OpenRouter区别?MAI Gateway(魔芋企业级AI网关)企业级方案对比指南
大数据·开发语言·人工智能·gateway·php·ai网关·mai gateway
点心的游戏开发世界8 小时前
GDScript 入门笔记(十一):Lambda 与匿名函数
开发语言·笔记·游戏引擎·godot
phltxy9 小时前
C语言操作符详解
java·c语言·算法
步行cgn10 小时前
@Configuration 详解:Spring 配置类的核心注解
java·后端·spring
sunshine22 girl10 小时前
Java学习一 环境配置2 安装和基本使用Idea
java·学习·intellij-idea
事圆则缓10 小时前
Kotlin 协程完全指南
开发语言·kotlin
我爱写代码i11 小时前
BeLink - 支持生成多种URL 缩短网址PHP源码
开发语言·php·短网址php源码
Java后端的Ai之路11 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式
嘿嘿-6611 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
统计学小王子12 小时前
数学建模国赛倒计时4天——《统计模型精讲(混合效应模型R语言实现)》
开发语言·数学建模·r语言