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#

May 07, 2017 am 10:17 AM

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

    //定义

    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(','));

    OtherType.Add(2, "2,22,222".Split(','));

    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<T> used to determine whether the keys in the dictionary are equal.
Count Get the number of key/value pairs contained in Dictionary<TKey, TValue>.
Item Gets or sets the value associated with the specified key.
Keys Get the collection containing the keys in Dictionary<TKey, TValue>.
Values ​​Get the collection containing the values ​​in Dictionary<TKey, TValue>.

Common methods
Name Description
Add Add the specified key and value to the dictionary.
Clear Remove all keys and values ​​from Dictionary<TKey, TValue>.
ContainsKey Determines whether Dictionary<TKey, TValue> contains the specified key.
ContainsValue Determines whether Dictionary<TKey, TValue> 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<TKey, TValue>.
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<TKey, TValue> 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<TKey, TValue>.
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!

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Active Directory with C#

Access Modifiers in C# Access Modifiers in C# Sep 03, 2024 pm 03:24 PM

Access Modifiers in C#

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Random Number Generator in C#

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

C# Data Grid View

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Patterns in C#

C# StringReader C# StringReader Sep 03, 2024 pm 03:23 PM

C# StringReader

C# StringWriter C# StringWriter Sep 03, 2024 pm 03:23 PM

C# StringWriter

BinaryWriter in C# BinaryWriter in C# Sep 03, 2024 pm 03:22 PM

BinaryWriter in C#

See all articles