【问题标题】:VB.NET: order dictionary alphabeticallyVB.NET:按字母顺序排列字典
【发布时间】:2012-03-14 06:03:41
【问题描述】:

我有一个字典(字符串,项目),我正在尝试按项目名称的字母顺序对其进行排序。我不想使用排序字典,没有它,我的运气为零。 Linq 不是我的强项...

Public Class Item
    Public Property name As String
    Public Property size As String
    Public Property price As Decimal
    Public Property timeMachine As Boolean
End Class

【问题讨论】:

  • 您应该实现 Isortable 和其他一些接口,或者使用 SortedDictionary 或其他实现这些接口的列表类。
  • 为什么不想使用 SortedDictionary?

标签: vb.net linq sorting dictionary


【解决方案1】:

Dictionary(Of TKey, TValue) 本质上是无序类型。没有办法对一个进行排序。尝试改用SortedDictionary(Of TKey, TValue)

Dim map = new SortedDictionary(Of String, Item)()

【讨论】:

    【解决方案2】:

    (1) 获取键列表,(2) 对键进行排序,(3) 根据排序后的键获取字典的值

    Dim keys As List(Of String) = dictionary.Keys.ToList
    keys.Sort()
    
    For Each str As String In Keys
      Console.WriteLine("{0} -> {1}", str, dictionary.Item(str))
    Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多