C#鍵值對容器


 

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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM