0

我知道我可以用 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
4

2 回答 2

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
于 2012-04-24T01:51:55.937 回答
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()
于 2012-04-23T21:14:18.313 回答