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



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值