本文主要是介绍C# 集合(五) —— Dictionary类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
总目录
C# 语法总目录
集合五 Dictionary
- 1. 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.exeif (!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# 语法总目录
这篇关于C# 集合(五) —— Dictionary类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!