C#中Dictionary的用法總結


可以實現通過鍵值查找、插入、刪除一個鍵-值對的操作,這些如果用數組實現都非常麻煩。

Key就是鍵,value就是值,

我們在很多地方都會用到字典,他的特點就是查找很快,當然比List快。

字典必須包含名空間System.Collection.Generic 

Dictionary里面的每一個元素都是一個鍵值對(由二個元素組成:鍵和值) 

鍵必須是唯一的,而值不需要唯一的
鍵和值都可以是任何類型(比如:string, int, 自定義類型,等等) 

 

常用屬性

    名稱    說明
    Comparer     獲取用於確定字典中的鍵是否相等的 IEqualityComparer<T>。
    Count        獲取包含在 Dictionary<TKey, TValue> 中的鍵/值對的數目。
    Item         獲取或設置與指定的鍵相關聯的值。
    Keys         獲取包含 Dictionary<TKey, TValue> 中的鍵的集合。
    Values       獲取包含 Dictionary<TKey, TValue> 中的值的集合。

常用方法
    名稱    說明
    Add                 將指定的鍵和值添加到字典中。
    Clear               從 Dictionary<TKey, TValue> 中移除所有的鍵和值。
    ContainsKey         確定 Dictionary<TKey, TValue> 是否包含指定的鍵。
    ContainsValue       確定 Dictionary<TKey, TValue> 是否包含特定值。
    Equals(Object)      確定指定的 Object 是否等於當前的 Object。 (繼承自 Object。)
    Finalize            允許對象在“垃圾回收”回收之前嘗試釋放資源並執行其他清理操作。 (繼承自 Object。)
    GetEnumerator       返回循環訪問 Dictionary<TKey, TValue> 的枚舉器。
    GetHashCode         用作特定類型的哈希函數。 (繼承自 Object。)
    GetObjectData       實現 System.Runtime.Serialization.ISerializable 接口,並返回序列化 Dictionary<TKey, TValue> 實例所需的數據。
    GetType             獲取當前實例的 Type。 (繼承自 Object。)
    MemberwiseClone     創建當前 Object 的淺表副本。 (繼承自 Object。)
    OnDeserialization    實現 System.Runtime.Serialization.ISerializable 接口,並在完成反序列化之后引發反序列化事件。
    Remove              從 Dictionary<TKey, TValue> 中移除所指定的鍵的值。
    ToString            返回表示當前對象的字符串。 (繼承自 Object。)
    TryGetValue         獲取與指定的鍵相關聯的值。

 

例子如下:

Person.cs

using System;

namespace SampleList
{
    class Person
    {
        public string name;
        public int age;

        //構造函數
        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
    }
}

 

CustomDictionary.cs

using System;
using System.Collections.Generic;

namespace SampleList
{
    class CustomDictionary
    {

        //定義一個字典變量
        static Dictionary<int, Person> dicPerson = new Dictionary<int, Person>();

        public static void LearnDictionaryInfo()
        {
            //添加鍵值 
            Person p1 = new Person("hjc", 22);
            Person p2 = new Person("tf", 21);
            dicPerson.Add(0, p1); //方式1
            dicPerson[1] = p2;    //方式2

            //取值
            Console.WriteLine("\n");
            Console.WriteLine("取值  name:" + dicPerson[0].name + "" + "age:" + dicPerson[0].age);

            //改值
            Console.WriteLine("\n");
            dicPerson[1].age = 20;
            Console.WriteLine("改值  name:" + dicPerson[1].name + "" + "age:" + dicPerson[1].age);

            //遍歷key
            Console.WriteLine("\n");
            Console.WriteLine("遍歷 key");
            foreach (int key in dicPerson.Keys)
            {
                string id = "用戶ID:" + key;
                string str = string.Format("name:{0} age:{1}", dicPerson[key].name, dicPerson[key].age);
                Console.WriteLine(id + "\t" + str);
            }

            //遍歷value
            Console.WriteLine("\n");
            Console.WriteLine("遍歷 value");
            foreach (Person value in dicPerson.Values)
            {
                string str = string.Format("name:{0} age:{1}", value.name, value.age);
                Console.WriteLine(str);
            }

            //遍歷字典
            Console.WriteLine("\n");
            Console.WriteLine("遍歷字典");
            foreach (KeyValuePair<int, Person> kvp in dicPerson)
            {
                string str = string.Format("key:{0}/name:{1}/age:{2}", kvp.Key, kvp.Value.name, kvp.Value.age);
                Console.WriteLine(str);
            }

            //  刪除元素
            Console.WriteLine("\n");
            Console.WriteLine("刪除元素");
            if (dicPerson.ContainsKey(1))    //如果存在
                dicPerson.Remove(1);
            foreach (Person value in dicPerson.Values)
            {
                string str = string.Format("name:{0} age:{1}", value.name, value.age);
                Console.WriteLine(str);
            }
            //清除所有的元素
            dicPerson.Clear();

            Console.Read();
        }

    }
}

 

如需轉載,還望表明出處,謝謝.......


免責聲明!

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



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