Home > Backend Development > C#.Net Tutorial > Introduction to sample code of Dictionary dictionary class in C#

Introduction to sample code of Dictionary dictionary class in C#

黄舟
Release: 2017-05-07 10:17:14
Original
1734 people have browsed it

Instructions
Must contain the namespace System.Collection.Generic
Each element in the Dictionary is a key-value pair (consisting of two elements: key and value)
The key must be unique, but the value does not need to be unique
Both the key and the value can be of any type (for example: string, int, custom type, etc.)
Through a key The time to read a value is close to O(1)
The partial order between key-value pairs does not need to be defined

Usage method:

    //定义
    Dictionary<string, string> openWith = new Dictionary<string, string>();
 

    //添加元素
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");
 

    //取值
    Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
 

    //更改值
    openWith["rtf"] = "winword.exe";
    Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
 

    //遍历key
    foreach (string key in openWith.Keys)
    {
        Console.WriteLine("Key = {0}", key);
    }
 

    //遍历value
    foreach (string value in openWith.Values)
    {
        Console.WriteLine("value = {0}", value);
    }

    //遍历value, Second Method
    Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
    foreach (string s in valueColl)
    {
        Console.WriteLine("Second Method, Value = {0}", s);
    }

 

    //遍历字典
    foreach (KeyValuePair<string, string> kvp in openWith)
    {
        Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    }
 

    //添加存在的元素
    try
    {
        openWith.Add("txt", "winword.exe");
    }
    catch (ArgumentException)
    {
        Console.WriteLine("An element with Key = \"txt\" already exists.");
    }
 

    //删除元素
    openWith.Remove("doc");
    if (!openWith.ContainsKey("doc"))
    {
        Console.WriteLine("Key \"doc\" is not found.");
    }
 
    //判断键存在
    if (openWith.ContainsKey("bmp")) // True 
    {
        Console.WriteLine("An element with Key = \"bmp\" exists.");
    }

    //参数为其它类型 
    Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>();
    OtherType.Add(1, "1,11,111".Split(&#39;,&#39;));
    OtherType.Add(2, "2,22,222".Split(&#39;,&#39;));
    Console.WriteLine(OtherType[1][2]);
 

//参数为自定义类型

//首先定义类

    class DouCube
    {
        public int Code { get { return _Code; } set { _Code = value; } } private int _Code;
        public string Page { get { return _Page; } set { _Page = value; } } private string _Page;
    } 

    //然后声明并添加元素
    Dictionary<int, DouCube> MyType = new Dictionary<int, DouCube>();
    for (int i = 1; i <= 9; i++)
    {
        DouCube element = new DouCube();
        element.Code = i * 100;
        element.Page = "http://www.doucube.com/" + i.ToString() + ".html";
        MyType.Add(i, element);
    }

    //遍历元素
    foreach (KeyValuePair<int, DouCube> kvp in MyType)
    {
        Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
    }
Copy after login

CommonAttributes

Name Description
Comparer Gets the IEqualityComparer used to determine whether the keys in the dictionary are equal.
Count Get the number of key/value pairs contained in Dictionary.
Item Gets or sets the value associated with the specified key.
Keys Get the collection containing the keys in Dictionary.
Values ​​Get the collection containing the values ​​in Dictionary.

Common methods
Name Description
Add Add the specified key and value to the dictionary.
Clear Remove all keys and values ​​from Dictionary.
ContainsKey Determines whether Dictionary contains the specified key.
ContainsValue Determines whether Dictionary contains a specific value.
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Finalize Allows an object to attempt to release resources and perform other cleanup operations before being recycled by Garbage Collection. (Inherited from Object.)
GetEnumerator Returns the enumerator that iterates through Dictionary.
GetHashCode is used as a hash function of a specific type. (Inherited from Object.)
GetObjectData Implements the System.Runtime.Serialization.ISerializable interface and returns the data required to serialize the Dictionary instance.
GetType Get the Type of the current instance. (Inherited from Object.)
MemberwiseClone Create a shallow copy of the current Object. (Inherited from Object.)
OnDeserialization Implements the System.Runtime.Serialization.ISerializable interface and triggers the deserialization event after deserialization is completed.
Remove                                                                                                                                           Remove the value of the specified key from Dictionary.
ToString Returns a string representing the current object. (Inherited from Object.)
TryGetValue Gets the value associated with the specified key.

The above is the detailed content of Introduction to sample code of Dictionary dictionary class in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template