C# 集合(五) —— Dictionary类

总目录
C# 语法总目录

集合五 Dictionary

1. Dictionary

字典是键值对集合,通过键值对来查找

  • Dictionary和Hashtable的区别是Dictionary可以用泛型,而HashTable不能用泛型

  • OrderedDictionary 是按照添加元素时的顺序的字典,是一个非泛型字典,可以用索引访问文员,也可以用键来访问元素,类似HashTable和ArrayList的结合

其他类型:

  • ListDictionary是使用一个独立链表来存储实际的数据,数据多时效率不好

  • HybridDictionary是为了解决ListDictionary数据多时效率不好的情况,用来替代ListDictionary。

  • SortedDictionary,内部由红黑树实现,内部根据键进行排序

//Hashtable

Hashtable hashtable = new Hashtable();
hashtable.Add("name", "lisi");
hashtable.Add("txt", "notepad.exe");
hashtable.Add("bmp", "paint.exe");
hashtable.Add("dib", "paint.exe");
hashtable.Add("rtf", "wordpad.exe");
try
{
    hashtable.Add("txt", "winword.exe");
}
catch (Exception)
{

    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

Console.WriteLine("For key = \"txt\", value = {0}.", hashtable["txt"]);

//An element with Key = "txt" already exists.
//For key = "txt", value = notepad.exe.

foreach (DictionaryEntry de in hashtable)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

//Key = dib, Value = paint.exe
//Key = bmp, Value = paint.exe
//Key = rtf, Value = wordpad.exe
//Key = name, Value = lisi
//Key = txt, Value = notepad.exe

if (!hashtable.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

//Dictionary

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

dics.Add("name", 123);
dics.TryAdd("name", 456);//如果有了键,那么就不会再添加了



dics.TryAdd("age", 50);
dics["age"] = 45;       //修改
dics.Remove("age");
dics.Remove("time");//不管有没有也不报错

Console.WriteLine(dics["name"]);

int value;
Console.WriteLine(dics.TryGetValue("name",out value));

Console.WriteLine(value);
//123
//True
//123

总目录
C# 语法总目录

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值