A detailed example of the use of C generic Dictionary
- 2020-09-28 09:06:58
- OfStack
This article provides an example of the use of the generic Dictionary in C#. It has very good practical value. Share to everybody for everybody reference. The details are as follows:
The most common use of generics is for generic collections. The namespace ES5en.Collections.Generic contains 1 collection class based on generics. Using generic collection classes can provide higher type safety, as well as higher performance, avoiding repeated boxing and unboxing of non-generic collections.
Many non-generic set classes have generic set classes. Here are the common non-generic set classes and their generic set classes:
非泛型集合类 | 泛型集合类 |
ArrayList | List<T> |
HashTable | DIctionary<T> |
Queue | Queue<T> |
Stack | Stack<T> |
SortedList | SortedList<T> |
The non-generic collection classes we use are ArrayList and HashTable. We often use HashTable to store the information to be written to the database or returned. In between, we need to carry out type transformation constantly, which increases the burden of system boxing and unboxing. If the data type we are manipulating is relatively certain, we use Dictionary
<
TKey,TValue
>
For example, when we need to store the user's shopping cart information (item name, corresponding number of items) in the e-commerce website, we can use Dictionary completely
<
string, int
>
To store shopping cart information without any type conversion.
Here are some simple examples, including declaring, populating, removing, and traversing key and value pairs:
Dictionary<string, string> myDic = new Dictionary<string, string>();
myDic.Add("aaa", "111");
myDic.Add("bbb", "222");
myDic.Add("ccc", "333");
myDic.Add("ddd", "444");
// If I add an existing key, add Method throws an exception
try
{
myDic.Add("ddd","ddd");
}
catch (ArgumentException ex)
{
Console.WriteLine(" This key already exists: " + ex.Message);
}
// To solve add() The exception method is to use ContainsKey() Method to determine whether a key exists
if (!myDic.ContainsKey("ddd"))
{
myDic.Add("ddd", "ddd");
}
else
{
Console.WriteLine(" This key already exists: ");
}
// With an indexer for negative values, if the build already exists, the key value of the existing key is changed without throwing an exception
myDic ["ddd"]="ddd";
myDic["eee"] = "555";
// When using an indexer to value, an exception is thrown if the key does not exist
try
{
Console.WriteLine(" A bond that doesn't exist ""fff"" The key value of is: " + myDic["fff"]);
}
catch (KeyNotFoundException ex)
{
Console.WriteLine(" No key found throws an exception: " + ex.Message);
}
// The solution to the above exception is to use ContarnsKey() To determine when there is a key, if you often want to take the value of the best use TryGetValue Method to get the corresponding key value in the collection
string value = "";
if (myDic.TryGetValue("fff", out value))
{
Console.WriteLine(" A bond that doesn't exist ""fff"" The key value of is: " + value );
}
else
{
Console.WriteLine(" The key value for the corresponding key was not found ");
}
// The following use foreach To iterate over the key-value pairs
// Generic structs Used to store value pairs
foreach (KeyValuePair<string, string> kvp in myDic)
{
Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
}
// Get the value set
foreach (string s in myDic.Values)
{
Console.WriteLine("value={0}", s);
}
// Get worth another 1 Kind of way
Dictionary<string, string>.ValueCollection values = myDic.Values;
foreach (string s in values)
{
Console.WriteLine("value={0}", s);
}
Common properties and methods are as follows:
常用属性 |
属性说明 |
|
Comparer |
获取用于确定字典中的键是否相等的 IEqualityComparer。 |
|
Count |
获取包含在 Dictionary中的键/值对的数目。 |
|
Item |
获取或设置与指定的键相关联的值。 |
|
Keys |
获取包含 Dictionary中的键的集合。 |
|
Values |
获取包含 Dictionary中的值的集合。 |
|
常用的方法 | 方法说明 | |
Add |
将指定的键和值添加到字典中。 |
|
Clear |
从 Dictionary中移除所有的键和值。 |
|
|
ContainsKey |
确定 Dictionary是否包含指定的键。 |
ContainsValue |
确定 Dictionary是否包含特定值。 |
|
Equals |
已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。) |
|
GetEnumerator |
返回循环访问 Dictionary的枚举数。 |
|
GetHashCode |
用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从Object 继承。) |
|
GetObjectData |
实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary实例所需的数据。 |
|
GetType |
获取当前实例的 Type。 (从 Object 继承。) |
|
OnDeserialization |
实现 System.Runtime.Serialization.ISerializable接口,并在完成反序列化之后引发反序列化事件。 |
|
ReferenceEquals |
确定指定的 Object实例是否是相同的实例。 (从 Object 继承。) |
|
Remove |
从 Dictionary中移除所指定的键的值。 |
|
ToString |
返回表示当前 Object的 String。 (从 Object 继承。) |
|
TryGetValue |
获取与指定的键相关联的值。 |
<?xml version="1.0" encoding="UTF-8"?>
<data>
<resource key="123">foo</resource>
<resource key="456">bar</resource>
<resource key="789">bar</resource>
</data>
i want to put this into a Dictionary (sorted) as key value pairs. i.e: 123:foo, 456:bar...etc
the keys are unknown.
string s = "<data><resource key=/"123/">foo</resource><resource key=/"456/">bar</resource><resource key=/"789/">bar</resource></data>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList resources = xml.SelectNodes("data/resource");
SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();
foreach (XmlNode node in resources){
dictionary.Add(node.Attributes["key"].Value, node.InnerText);
}
linq to xml:
var xml = XDocument.Load(...);
var sequence = from e in xml.Root.Elements()
let key = (string)e.Attribute("key")
order by key
select new {
Key = key,
Value = (string)e
};
Hopefully this article has helped you with your C# programming.