上篇有简单总结了列表性质的结合,下篇主要试着研究下键-值对集合。
1.Dictionary
有序,key不能为null,key区分大小写,不能添加重复的key,但可以有重复的value。
相当于Java的map。
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("a", "A");
dic.Add("null", null);
dic.Add("b", "B");
var vv = dic["a"];
foreach (var item in dic)
{
Console.WriteLine("key:{0},value:{1}", item.Key, item.Value);
}
获取value,用dic[key]
2.SortedDictionary
SortedDictionary除了拥有Dictionary的特点外,还能让集合类元素排序
SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
//Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("a", "A");
dic.Add("null", null);
dic.Add("b", "B");
dic.Add("a1", "A");
foreach (var item in dic)
{
Console.WriteLine("key:{0},value:{1}", item.Key, item.Value);
}
输出:A,A,B
3.Hashtable
有序,key不能为空
Hashtable table = new Hashtable();
table.Add("a", 1);
table.Add("b", 2);
//table.Add(null, "a");
table.Remove("a");
foreach (DictionaryEntry item in table)
{
Console.WriteLine(item.Key);
}
关于Hashtable和dictionary性能上的区别,参照 http://www.cnblogs.com/zcy_soft/archive/2010/10/02/1841165.html
4.SortedList
有序,key不能为null,key不重复。
SortedList list = new SortedList();
list.Add("a", "A");
list.Add("b", "B");
list.Add("1", "1");
foreach (DictionaryEntry item in list)
{
Console.WriteLine(item.Key + " " + item.Value);
}
补充:
上面的集合键值对都是1-1对应的,如果遇到一对多,可以将多个value组合成一个list,再来对应可以
也可以用LookUp,,参考:http://www.cnblogs.com/multiplesoftware/archive/2011/03/31/2000528.html