C#键值对容器的介绍

 更新时间:2020年6月25日 11:41  点击:1454

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 = https://www.jb51.net/dgjack/archive/2012/03/03/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;

[!--infotagslink--]

相关文章