SoFunction
Updated on 2025-04-05

Example analysis of basic usage of Dictionary

This article describes the basic usage of Dictionary. Share it for your reference, as follows:

//Dictionary is located under the namespace/*
  * The namespace must be referenced before using Dictionary;
  * When using Dictionary, the data type of its key and value must be declared (can be any type);
  */
//Declare instantiation of Dictionary to dic<int, string> dic = new <int, string>();
//Add keys and values ​​for dic(100, "quber100");
(200, "quber200");
//Check whether the key 300 existsif (!(300))
{
  //Add 300 (key) and corresponding quber300 (value) added  (300, "quber300");
}
//Remove the item with dic key of 300(300);
//Get the total number of dic key-value pairsint dicCount = ;
("Loop to get keys and values ​​in dic:<br/>");
//Loop to get keys and values ​​in dicforeach (KeyValuePair&lt;int, string&gt; keyDic in dic)
{
  ("key:" +  + ",value:" +  + "&lt;br/&gt;");
}
("&lt;hr/&gt;&lt;br/&gt;");
("Loop to get the key in dic:<br/>");
//Loop to get the key in dicDictionary&lt;int, string&gt;.KeyCollection keyDics = ;
foreach (int iKey in keyDics)
{
  ("key:" + iKey + "&lt;br/&gt;");
}
("&lt;hr/&gt;&lt;br/&gt;");
("Another way to loop to get the key in dic:<br/>");
//Loop to get the key in dicforeach (int iKey in )
{
  ("key:" + iKey + "&lt;br/&gt;");
}
("&lt;hr/&gt;&lt;br/&gt;");
("Loop to get the value in dic:<br/>");
//Loop to get the value in dicDictionary&lt;int, string&gt;.ValueCollection valueDics = ;
foreach (string strValue in valueDics)
{
  ("value:" + strValue + "&lt;br/&gt;");
}
("&lt;hr/&gt;&lt;br/&gt;");
("Another way to loop to get the value in dic:<br/>");
//Loop to get the value in dicforeach (string strValue in )
{
  ("value:" + strValue + "&lt;br/&gt;");
}
("&lt;hr/&gt;&lt;br/&gt;");
("Get individual keys and values ​​in dic:<br/>");
("key:100,value:" + dic[100] + "&lt;br/&gt;");
("&lt;hr/&gt;&lt;br/&gt;");
("Check whether the key (100) exists in dic and return its value dicStr:<br/>");
//Check whether there is a key (100) in dic and return its value dicStrstring dicStr = ;
if ((100, out dicStr))
{
  ("OK");
}
else
{
  ("NO");
}
("&lt;hr/&gt;&lt;br/&gt;");

For more information about relevant content, please view the topic of this site:Summary of operation json skills》、《Summary of string operation techniques》、《Summary of operating XML skills》、《Summary of file operation skills》、《Ajax tips summary topic"and"Summary of cache operation skills》。

I hope this article will be helpful to everyone's programming.