C # dictionary instance for storing multiple values of the same key

Time:2021-2-13

Two issues are involved

1、 Access the folder on disk and the folder under the folder

Let’s look at the disk folder structure first

There is a root folder named savefile under Disk C, and two subfolders named 2018 and 2019 under savefile,

There are two subfolders 18120 and 18131 under the sub file

There are two subfolders 18120 and 18129 under the sub file

Now I want to save the name of the savefile subfolder and the folder under the subfolder, which is as follows

2018       18120

       18131

2019  18120

     18129

2、 Based on the above structure, how do we store data

In fact, I didn’t get around it at first. At first, I thought of using dictionary and key value pair to store data. But at first, I didn’t think so much about it. I just ran around and found a problem

The same key cannot exist???? Suddenly a little confused, I don’t know how to write. At this time, I thought of using hashtable

Here is a simple way to use hashtable

using System;
using System.Collections;

namespace CollectionsApplication
{
 class Program
 {
 static void Main(string[] args)
 {
  Hashtable ht = new Hashtable();

  ht.Add("001", "Zara Ali");
  ht.Add("002", "Abida Rehman");
  ht.Add("003", "Joe Holzner");
  ht.Add("004", "Mausam Benazir Nur");
  ht.Add("005", "M. Amlan");
  ht.Add("006", "M. Arif");
  ht.Add("007", "Ritesh Saikia");

  if (ht.ContainsValue("Nuha Ali"))
  {
  Console.WriteLine("This student name is already in the list");
  }
  else
  {
  ht.Add("008", "Nuha Ali");
  }
  //Gets the collection of keys 
  ICollection key = ht.Keys;

  foreach (string k in key)
  {
  Console.WriteLine(k + ": " + ht[k]);
  }
  Console.ReadKey();
 }
 }

There’s a problem with hashtable and dictionary, and they can’t have the same key. So I prefer to use dictionary. Let’s try to finish it with dictionary,

using Systemusing System.Collections;namespace CollectionsApplication{ class Program {

    private const string SavePath = @"C:\SavaFile\";
 Public static list < string > yearstr = new list < string > () {}; // save year
 //Storage year and number
 public static Dictionary<string,List<string>> dic = new Dictionary<string,List<string>>() { };
 static void Main(string[] args)
 {
    #region
  Directoryinfo basedir = new directoryinfo (savepath); // read the subdirectory under the path of C: // savafile \
      DirectoryInfo[] dii =  baseDir.GetDirectories (); // save the savefile folder subdirectory
foreach (var item in dii) {  dic.Add ( item.Name ,null);  YearStr.Add ( item.Name ); // add the savefile folder to the yearstr collection
  }
  DirectoryInfo dir; 
  foreach (var item in YearStr)
  {
   Dir = new directoryinfo (savepath + @ "\" + item); // save the subdirectory directoryinfo [] DIIS in the subdirectory of the savefile folder= dir.GetDirectories ();
  List < string > panlelst = new list < string > () {}; // used to save value
  foreach (var item2 in diis)
  {
   if ( dic.ContainsKey (item)) // if the dictionary contains a key
   {
   Panlelst.Add (Item2. Name); // add the value to the value set
   DIC [item] = panlelst; // assign to the corresponding key
   } 
  }
  }
  //Traverse dictionary
  foreach (KeyValuePair<string, List<string>> kvp in dic)
  {
  foreach (var item in kvp.Value)
  {
   Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, item);
  }  
  }
  Console.ReadLine(); 
  #endregion
 }
 }

OK, I tried it,

Take a look at the output

Post some common usages of dictionary again

static void Main(string[] args)
 {
  //Create a generic hash table with the key type of int and the value type of string
  Dictionary<int, string> myDictionary = new Dictionary<int, string>();
  //1. Add elements
  myDictionary.Add(1, "a");
  myDictionary.Add(2, "b");
  myDictionary.Add(3, "c");
  //2. Delete element
  myDictionary.Remove(3);
  //3. If there is no element, add the element
  if (!myDictionary.ContainsKey(4))
  {
  myDictionary.Add(4, "d");
  }
  //4. Display capacity and number of elements
  Console.WriteLine (number of elements: {0}), myDictionary.Count );
  //5. Find elements by key
  if (myDictionary.ContainsKey(1))
  {
  Console.WriteLine("key:{0},value:{1}","1", myDictionary[1]);
  Console.WriteLine(myDictionary[1]);  
  }
  //6. Traversing elements through keyvaluepair
  foreach (KeyValuePair<int,string>kvp in myDictionary)
  {
  Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);

  }
  //7. Get the set of hash table keys
  Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys;
  //Traversing the set of keys
  foreach (int n in keyCol)
  {
   Console.WriteLine("key={0}", n);  
  }
  //8. Get the set of hash table values
  Dictionary<int, string>.ValueCollection valCol = myDictionary.Values;
  //Traverse the collection of values
  foreach( string s in valCol)
  {
  Console.WriteLine("value:{0}",s);
  }
  //9. Use the TryGetValue method to get the value corresponding to the specified key
  string slove = string.Empty;
  if (myDictionary.TryGetValue(5, out slove))
  {
  Console.WriteLine ("search result: {0}", slope));
  }
  else
  {
  Console.WriteLine ("find failed");
  }
  //10. Clear hash table
  //myDictionary.Clear();
  Console.ReadKey();
 }
Add: the difference between hashtable and dictionary

1.HashTable

A hash table represents a collection of key / value pairs. In. Net framework, hashtable is System.Collections Namespace provides a container for processing and representing key value pairs similar to key value, in which key can be used for quick search, and key is case sensitive; value is used to store the value corresponding to key. The key value pairs in hashtable are all of object type, so hashtable can support any type of key value pairs, and any non null object can be used as a key or value.

Add a key / key value pair to the hash table: HashtableObject.Add (key,);

To remove a key / key value pair from the hash table: HashtableObject.Remove (key);

Remove all elements from the hash table: HashtableObject.Clear ();

Determine whether the hash table contains a specific key key: HashtableObject.Contains (key);

2.Dictionary

A dictionary represents a collection of keys and values.

Dictionary < string, string > is a generic

It has the function of collection. Sometimes it can be regarded as an array

His structure is as follows: Dictionary < [key], [value] >

Its characteristic is that the stored object needs to be stored in the generic corresponding to the [key] value one by one

Find the corresponding value through a certain [key]

3. Differences between hashtable and Dictionary: https://www.jb51.net/article/182337.htm

(1) . hashtable does not support generics, while dictionary supports generics.

(2) The element of. Hashtable belongs to the object type, so boxing and unboxing operations usually occur when storing or retrieving value types, so you may need to do some type conversion operations, and boxing operations are also needed for int and float value types, which is very time-consuming.

(3) Dictionary is recommended for single threaded programs, which has the advantages of generics, faster reading speed and more full utilization of capacity. Hashtable is recommended in multithreaded programs. The default hashtable allows single thread writing and multi thread reading. Further calling synchronized() method on hashtable can obtain a completely thread safe type. Dictionary is not thread safe and must be protected by using lock statement artificially, which greatly reduces the efficiency.

(4) When passing the code test, it is found that the efficiency of key is integer type, and dictionary is faster than hashtable. If the key is string type, the efficiency of dictionary is not as fast as hashtable.

OK, that’s all for today’s sharing. If you have any questions, please point them out.

So far, this article about C # storing the same key and multiple values of the dictionary example detailed explanation is introduced here, more related to C # storing the same key and multiple values of the dictionary method content, please search the previous articles of developer or continue to browse the following related articles, hope you can support developer more in the future!