C#键值对容器

本文对比了.NET框架中几种常见的键值对容器,包括StringDictionary、NameValueCollection、KeyedCollection等,并介绍了它们的区别及应用场景。此外,还详细讨论了Dictionary泛型容器的使用方法。
 

StringDictionary:默认key不区分大小写
NameValueCollection:默认key区分大小写
KeyedCollection:不是键值对容器,但是比键值对容器更好用,强烈推荐

命名空间using System.Collections.Specialized

System.Collections 命名空间包含接口和类,这些接口和类定义各种对象(如列表、队列、位数组、哈希表和字典)的集合。
System.Collections.Generic 命名空间包含定义泛型集合的接口和类,泛型集合允许用户创建强类型集合,它能提供比非泛型强类型集合更好的类型安全性和性能。
System.Collections.Specialized 命名空间包含专用的和强类型的集合,例如,链接的列表词典、位向量以及只包含字符串的集合。

Hashtable、SortedList
SortedList为可排序的字典,当添加元素时,元素按照正确的排序顺序插入SortedList,同时索引自动进行相应的调整,移除元素亦然。
Hashtable、SortedList的键和值均为object类型,因此使用的时候,转化比较频繁

dictionary
范型Dictionary,可以随便制定key,value的类型
Dictionary <String, String> dic = new Dictionary <string, string> ();
dic.Add( "1 ", "Jerry ");
dic.Add( "2 ", "Kimmy ");
dic.Add( "3 ", "Tommy ");

 

也可以自己定义类来使用

public class KeyValueItem
    {
        private int _Value;
        public int Value
        {
            get
            {
                return _Value;
            }
        }
        private string _Name;
        public string Name
        {
            get
            {
                return _Name;
            }
        }
        //
        public KeyValueItem(string name, int value)
        {
            _Name = name;
            _Value = value;
        }
        public override string ToString()
        {
            return _Name;
        }
    }

插入值的时候:

KeyValueItem it = new KeyValueItem("客户1", 1);
            comboBox1.Items.Add(it);
            it = new KeyValueItem("客户2", 2);
            comboBox1.Items.Add(it);
            it = new KeyValueItem("客户3", 3);
            comboBox1.Items.Add(it);

取值的时候就用 :

int relationtype = ((KeyValueItem)comboBox1.SelectedItem).Value;

转载于:https://www.cnblogs.com/dgjack/archive/2012/03/03/2378531.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值