2012-04-23 78 views
0

我知道我可以用for循環做這件事,因此我現在正在做這件事。我希望有一個更有效的方式來完成這項任務。篩選字典返回列表

我有一個字典(整數,布爾) 或字符串,布爾值。 我想從字典中得到一個列表(整數)或字符串,其中所有的值都是真實的(或假的取決於我當時需要什麼)

並將其推廣或「黑匣子」它可以是任何字典(無論什麼) 並返回一個列表(無論什麼)值=無論我當時在找什麼。

字符串,字符串,其中值= 「關閉」

短:我想所有鍵的所有名單誰的價值=一些標準

我當前的代碼:

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 
+0

我認爲For循環可能是您最好的選擇。但我可能是錯的 – 2012-04-23 21:03:48

+0

另外,我可以像myList.Find(標準)或myList.FindAll(標準),有沒有一個字典相當? – JeZteR 2012-04-23 21:26:08

回答

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

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