Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Dictionary in C #

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to use Dictionary in C#. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Usage 1: general use

It is necessary to determine whether the key exists before adding a key-value pair, and if the key already exists and does not, an exception will be thrown. So it's troublesome to make a judgment every time, and an extension method is used in the remarks.

Public static void DicSample1 ()

{

Dictionary pList = new Dictionary ()

Try

{

If (pList.ContainsKey ("Item1") = = false)

{

PList.Add ("Item1", "ZheJiang")

}

If (pList.ContainsKey ("Item2") = = false)

{

PList.Add ("Item2", "ShangHai")

}

Else

{

PList ["Item2"] = "ShangHai"

}

If (pList.ContainsKey ("Item3") = = false)

{

PList.Add ("Item3", "BeiJiang")

}

}

Catch (System.Exception e)

{

Console.WriteLine ("Error: {0}", e.Message)

}

/ / determine whether there is a corresponding key and display it

If (pList.ContainsKey ("Item1"))

{

Console.WriteLine ("Output:" + pList ["Item1"])

}

/ / traversing Key

Foreach (var key in pList.Keys)

{

Console.WriteLine ("Output Key: {0}", key)

}

/ / traversing Value

Foreach (String value in pList.Values)

{

Console.WriteLine ("Output Value: {0}", value)

}

/ / traversing Key and Value

Foreach (var dic in pList)

{

Console.WriteLine ("Output Key: {0}, Value: {1}", dic.Key, dic.Value)

}

}

The Value of usage 2:Dictionary is an array.

/ / /

/ the Value of Dictionary is an array

/ / /

Public static void DicSample2 ()

{

Dictionary dic = new Dictionary ()

String [] ZheJiang = {"Huzhou", "HangZhou", "TaiZhou"}

String [] ShangHai = {"Budong", "Buxi"}

Dic.Add ("ZJ", ZheJiang)

Dic.Add ("SH", ShangHai)

Console.WriteLine ("Output:" + dic ["ZJ"] [0])

}

Usage 3: Value of Dictionary is a class

/ / Value of Dictionary is a class

Public static void DicSample3 ()

{

Dictionary stuList = new Dictionary ()

Student stu = null

For (int I = 0; I < 3; iTunes +)

{

Stu = new Student ()

Stu.Name = i.ToString ()

Stu.Name = "StuName" + i.ToString ()

StuList.Add (i.ToString (), stu)

}

Foreach (var student in stuList)

{

Console.WriteLine ("Output: Key {0}, Num: {1}, Name {2}", student.Key, student.Value.Name, student.Value.Name)

}

}

Student class:

Public class Student

{

Public String Num {get; set;}

Public String Name {get; set;}

}

The extension method of Dictionary uses the

/ / /

/ the extension method of Dictionary uses

/ / /

Public static void DicSample4 ()

{

/ / 1) ordinary call

Dictionary dict = new Dictionary ()

DictionaryExtensionMethodClass.TryAdd (dict, 1, "ZhangSan")

DictionaryExtensionMethodClass.TryAdd (dict, 2, "WangWu")

DictionaryExtensionMethodClass.AddOrPeplace (dict, 3, "WangWu")

DictionaryExtensionMethodClass.AddOrPeplace (dict, 3, "ZhangWu")

DictionaryExtensionMethodClass.TryAdd (dict, 2, "LiSi")

/ / 2) TryAdd and AddOrReplace have strong self-description ability, which is easy to use and simple:

Dict.AddOrPeplace (20, "Orange")

Dict.TryAdd (21, "Banana")

Dict.TryAdd (22, "apple")

/ / 3) write together like Linq or jQuery

Dict.TryAdd (10, "Bob")

.TryAdd (11, "Tom")

.AddOrPeplace (12, "Jom")

/ / 4) get the value

String F = "Ba"

Dict.TryGetValue (31, out F)

Console.WriteLine ("F: {0}", F)

Foreach (var dic in dict)

{

Console.WriteLine ("Output: Key: {0}, Value: {1}", dic.Key, dic.Value)

}

/ / 5) the following is to get the value using GetValue

Var v1 = dict.GetValue (111 dint null)

Var v2 = dict.GetValue (10, "abc")

/ / 6) batch add

Var dict1 = new Dictionary ()

Dict1.AddOrPeplace (3,3)

Dict1.AddOrPeplace (5,5)

Var dict2 = new Dictionary ()

Dict2.AddOrPeplace (1,1)

Dict2.AddOrPeplace (4,4)

Dict2.AddRange (dict1, false)

}

Extend the class where the method is located

Public static class DictionaryExtensionMethodClass

{

/ / /

/ try to add keys and values to the dictionary: add them if they do not exist; do not add or throw constants if they do not exist.

/ / /

Public static Dictionary TryAdd (this Dictionary dict, TKey key, TValue value)

{

If (dict.ContainsKey (key) = = false)

Dict.Add (key, value)

Return dict

}

/ / /

/ / add or replace keys and values to the dictionary: if they do not exist, add them; if they exist, replace them

/ / /

Public static Dictionary AddOrPeplace (this Dictionary dict, TKey key, TValue value)

{

Dict [key] = value

Return dict

}

/ / /

/ gets the value associated with the specified key, and returns the default value entered if not available

/ / /

Public static TValue GetValue (this Dictionary dict, TKey key, TValue defaultValue)

{

Return dict.ContainsKey (key)? dict [key]: defaultValue

}

/ / /

/ / add a batch of key-value pairs to the dictionary

/ / /

/ / if it already exists, whether to replace it

Public static Dictionary AddRange (this Dictionary dict, IEnumerable values, bool replaceExisted)

{

Foreach (var item in values)

{

If (dict.ContainsKey (item.Key) = = false | | replaceExisted)

Dict [item.Key] = item.Value

}

Return dict

}

}

This is how Dictionary is used in C# shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report