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]]);
        }
    }
    
}
相关推荐
Faith-小浩浩几秒前
macos 多个版本的jdk
java·macos·jdk
喵手7 分钟前
Java异常处理最佳实践:如何避免捕获到不必要的异常?
java·后端·java ee
猿java19 分钟前
精通MySQL却不了解OLAP和 OLTP,正常吗?
java·后端·面试
ankleless24 分钟前
Python 数据可视化:Matplotlib 与 Seaborn 实战
开发语言·python
渣哥32 分钟前
面试官:为什么阿里巴巴要重写HashMap?ConcurrentHashMap哪里不够用?
java
喵手34 分钟前
Java中的HashMap:你了解它的工作原理和最佳实践吗?
java·后端·java ee
Gavin_91538 分钟前
一文速通Ruby语法
开发语言·ruby
weixin_4565881538 分钟前
【java面试day16】mysql-覆盖索引
java·mysql·面试
心月狐的流火号40 分钟前
计算机I/O模式演进与 Java NIO 直接内存
java·操作系统