c#集合類彙總(下)

上篇有簡單總結了列表性質的結合,下篇主要試着研究下鍵-值對集合。

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章