散列哈希表的原因

时间:2009-05-29 04:15:32

标签: .net vb.net sorting hash hashtable

雇主要求我对哈希表进行排序。我一直认为哈希表的使用方式是非排序友好的。我错了想到这个,如果没有,你能指点我好的VB.Net(是现在杀了我,但这是一个旧系统)排序哈希表的方法。

感谢。

3 个答案:

答案 0 :(得分:5)

我有过几种情况,我从文件中读取名称 - 值对,需要按照它们在文件中列出的顺序保留它们,但也需要O(1)查找时间。排序的哈希表是我如何完成两者的。

对于.NET 1.1,请使用System.Collections.SortedList。对于.NET 2.0+,请使用System.Collections.Generic.SortedDictionary。

答案 1 :(得分:1)

我喜欢DocMax's answer

另一种选择:
按照SortedList或SortedDictionary正在做的事情来推动您自己的解决方案:

  1. 将哈希表键(或值)放入数组
  2. 排序数组
  3. 迭代数组并输出排序数据
  4. (代码稍微修改自here

    Option Strict On
    
    Imports System.Collections
    
    Public Module modMain
     Public Sub Main()
      Dim myHashTable As New Hashtable
    
      myHashTable.Add("C", "3")
      myHashTable.Add("A", "1")
      myHashTable.Add("B", "2")
    
      Dim keys As ICollection = myHashTable.Keys
      Dim keysArray(myHashTable.Count - 1) As String 
    
      keys.CopyTo(keysArray, 0)
      Array.Sort(keysArray)
      For Each key As String in keysArray
         Console.WriteLine("{0} is {1}", key, myHashTable(key))
      Next
     End Sub
    End Module
    

    Option Strict On Imports System.Collections Public Module modMain Public Sub Main() Dim myHashTable As New Hashtable myHashTable.Add("C", "3") myHashTable.Add("A", "1") myHashTable.Add("B", "2") Dim keys As ICollection = myHashTable.Keys Dim keysArray(myHashTable.Count - 1) As String keys.CopyTo(keysArray, 0) Array.Sort(keysArray) For Each key As String in keysArray Console.WriteLine("{0} is {1}", key, myHashTable(key)) Next End Sub End Module

答案 2 :(得分:0)

尝试使用队列:

当您需要获得遵循FIFO(先进先出)规则所需的内容时,大多数OOP(例如Java,.NET)都会使用队列。

堆叠是LIFO - 先进先出......

Dim myQ As Queue(Of KeyValuePair(Of Integer, String)) = New Queue(Of KeyValuePair(Of Integer, String))

myQ.Enqueue(New KeyValuePair(Of Integer, String)(1, "one"))
myQ.Enqueue(New KeyValuePair(Of Integer, String)(2, "two"))
myQ.Enqueue(New KeyValuePair(Of Integer, String)(3, "three"))

'later on you can retrieve objects by
'myQ.Dequeue
Response.Write("<p>Queue</p>")
For Each kvp As KeyValuePair(Of Integer, String) In myQ
    Response.Write(kvp.Key & " is " & kvp.Value & "<br>")
Next

Dim ht As Hashtable = New Hashtable()
ht.Add(1, "one")
ht.Add(2, "two")
ht.Add(3, "three")
Response.Write("<p>Hashtable</p>")
For Each kvp As DictionaryEntry In ht
    Response.Write(kvp.Key & " is " & kvp.Value & "<br>")
Next