2017-01-16 36 views
-1

我有兩個問題:如何使用哈希表C#

  1. 是什麼一個Hashtable和詞典之間的區別?

  2. 是否有任何可能的方法將這些集合中的任何一個保存到磁盤?

+0

請使用MSDN ... – Mat

+0

爲了給你一個好的答案,它可能會幫助我們,如果你有一個問題,如果你還沒有看過。如果你可以提供[mcve],它可能也很有用。 – Mat

+0

@Mat你是對的,但我只需要知道第二個問題的答案(當我添加項目的時候......) – InvBoy

回答

2

首先,不要使用散列表。改用HashSet。您可以在名稱空間System.Collections.Generic中找到它。

什麼是散列圖?

散列圖(或字典,因爲它在C#中調用)是一種數據結構,允許您使用其他類型的輸入來查找一種類型的數據。基本上,當您向字典中添加項目時,可以同時指定密鑰。然後,當你想查找字典中的值時,只需給它一個鍵,它就會給你與它相關的值。

例如,如果您有一堆您希望能夠通過其UPC查找的產品對象,則可以將產品添加到您的字典中,將產品作爲值並將UPC編號作爲關鍵字。

A HashSet另一方面,不存儲成對的鍵和值。它只是存儲物品。哈希集合(或任何集合)確保在將項目添加到集合時,不會有重複項目。

當我在哈希表中添加項目時,我可以將它保存爲新文件並還原原始項目?

首先,不要使用散列表。改爲使用HashSet。你可以在命名空間System.Collections.Generic中找到它。要使用它,只需將其中的項目添加到其中,就像您使用其他任何收藏一樣。

像其他收藏,HashSet支持系列化連載是當你把一個對象,並將其轉換爲字節的字符串,因此它可以被保存到一個文件或通過互聯網發送)。下面是顯示了散列組的序列化的一個範例程序:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 

namespace HashSetSerializationTest 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var set = new HashSet<int>(); 
     set.Add(5); 
     set.Add(12); 
     set.Add(-50006); 

     Console.WriteLine("Enter the file-path:"); 
     string path = Console.ReadLine(); 
     Serialize(path, set); 
     HashSet<int> deserializedSet = (HashSet<int>)Deserialize(path); 

     foreach (int number in deserializedSet) 
     { 
      Console.WriteLine($"{number} is in original set: {set.Contains(number)}"); 
     } 
     Console.ReadLine(); 
    } 

    static void Serialize(string path, object theObjectToSave) 
    { 
     using (Stream stream = File.Create(path)) 
     { 
      var formatter = new BinaryFormatter(); 
      formatter.Serialize(stream, theObjectToSave); 
     } 
    } 

    static object Deserialize(string path) 
    { 
     using (Stream stream = File.OpenRead(path)) 
     { 
      var formatter = new BinaryFormatter(); 
      return formatter.Deserialize(stream); 
     } 
    } 
} 
} 

爲了序列什麼,你需要包括System.IOSystem.Runtime.Serialization.Formatters.Binary