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]]);
        }
    }
    
}
相关推荐
云深麋鹿21 小时前
数据链路层总结
java·网络
fire-flyer1 天前
响应式客户端 WebClient详解
java·spring·reactor
Pocker_Spades_A1 天前
Python快速入门专业版(二十六):Python函数基础:定义、调用与返回值(Hello函数案例)
开发语言·python
北执南念1 天前
基于 Spring 的策略模式框架,用于根据不同的类的标识获取对应的处理器实例
java·spring·策略模式
王道长服务器 | 亚马逊云1 天前
一个迁移案例:从传统 IDC 到 AWS 的真实对比
java·spring boot·git·云计算·github·dubbo·aws
island13141 天前
【C++框架#5】Elasticsearch 安装和使用
开发语言·c++·elasticsearch
华仔啊1 天前
为什么 keySet() 是 HashMap 遍历的雷区?90% 的人踩过
java·后端
9号达人1 天前
Java 13 新特性详解与实践
java·后端·面试
橙序员小站1 天前
搞定系统设计题:如何设计一个支付系统?
java·后端·面试
周周记笔记1 天前
学习笔记:Python的起源
开发语言·python