2017-01-16 106 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