过滤字典以返回列表

时间:2012-04-23 20:58:12

标签: vb.net

我知道我可以用for循环来做到这一点,这就是我现在正在做的事情。我希望有一种更有效的方法来完成任务。

我有一本字典(Of Integer,Boolean) 或Of String,布尔值。 我想从字典中获取一个列表(整数)或Of String,其中所有值都为真(或者取决于我当时需要的假)

并概括它或“黑匣子”它,它可以是任何字典(无论如何,等等) 并返回一个列表(无论如何),其中值=我当时正在寻找的东西。

string,string其中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

2 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:1)

使用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()