【问题标题】:Filter a Dictionary to return a list过滤字典以返回列表
【发布时间】:2012-04-24 09:51:55
【问题描述】:

我知道我可以使用 for 循环来做到这一点,因为我现在就是这样做的。我希望有一种更有效的方式来完成这项任务。

我有一本字典(整数,布尔值) 或字符串,布尔值。 我想从字典中获取一个列表(整数)或字符串,其中所有值都是真(或假,取决于我当时需要什么)

为了概括它或“黑盒”它,它可以是任何字典(无论什么,什么) 并返回一个列表(不管),其中值 = 我当时正在寻找的任何东西。

字符串,字符串 where value = "Closed"

简而言之:我想要所有键值的所有列表 = 一些标准

我当前的代码:

    Public Function FindInDict(Of tx, ty)(thedict As Dictionary(Of tx, ty), criteria As ty) As List(Of tx)
    Dim tmpList As New List(Of tx)

    For xloop As Integer = 0 To thedict.Count - 1
        If CType(thedict(thedict.Keys(xloop)), ty).Equals(criteria) Then
            tmpList.Add(thedict.Keys(xloop))
        End If
    Next
    Return tmpList
End Function

【问题讨论】:

  • 我认为 For 循环可能是你最好的选择。但我可能错了
  • 另外,我可以像 myList.Find(criteria) 或 myList.FindAll(criteria) 那样做,有没有等效的字典?

标签: vb.net


【解决方案1】:

您可以使用 Linq 轻松做到这一点:

Public Function FindInDict(Of tx, ty)(thedict As Dictionary(Of tx, ty), criteria As ty) As List(Of tx)
    Return (From kvp In thedict
            Where kvp.Value.Equals(criteria)
            Select kvp.key).ToList()
End Function

【讨论】:

    【解决方案2】:

    使用 LINQ,如下所示:

    Dim tStorage As Dictionary(Of String, String) = New Dictionary(Of String, String)
    Dim tKeys As List(Of String) = New List(Of String)
    Dim tCriteria As List(Of String) = New List(Of String)
    
    tStorage.Add("One", "Uno")
    tStorage.Add("Two", "Dos")
    tStorage.Add("Three", "Tres")
    tStorage.Add("Four", "Quatro")
    
    tCriteria.Add("Dos")
    tCriteria.Add("Quatro")
    
    tKeys = (From k In tStorage.Keys Where tCriteria.Contains(tStorage(k)) Select k).ToList
    
    For Each tKey As String In tKeys
        Console.WriteLine(tKey)
    Next
    
    Console.ReadKey()
    

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      相关资源
      最近更新 更多