2013-08-01 24 views
3

有人可以告訴我,我怎麼可以只搜索字典中的一個鍵的一部分(在VB.NET中)?如何搜索字典鍵的一部分?

我用下面的示例代碼:

Dim PriceList As New Dictionary(Of String, Double)(System.StringComparer.OrdinalIgnoreCase) 

    PriceList.Add("Spaghetti alla carbonara", 21.65) 
    PriceList.Add("Spaghetti aglio e olio", 22.65) 
    PriceList.Add("Spaghetti alla napoletana", 23.65) 
    PriceList.Add("Spaghetti alla puttanesca ", 24.65) 
    PriceList.Add("Spaghetti alla gricia ", 25.65) 
    PriceList.Add("Spaghetti alle vongole", 26.65) 
    PriceList.Add("Spaghetti Bolognese", 27.65) 

    If PriceList.ContainsKey("spaghetti bolognese") Then 
     Dim price As Double = PriceList.Item("spaghetti bolognese") 
     Console.WriteLine("Found, price: " & price) 
    End If 

    If Not PriceList.ContainsKey("Bolognese") Then 
     Console.WriteLine("How can I search for only a part of a key?") 
    End If 

如果我只知道像「肉醬」鍵或只是一個像「大刀」字的一部分,我怎麼可以搜索這個部分的一部分完整的密鑰?

回答

7

您可以檢查是否有其使用Any()

If Not PriceList.Where(Function(x) x.Key.Contains("Bolognese")).Any() 
    Console.WriteLine("No Bolognese, sorry") 
End If 

含有「肉醬」一鍵搞定的字典子集包含「肉醬」唯一密鑰的任何條目:

Dim subsetOfDictionary = PriceList _ 
     .Where(Function(x) x.Key.Contains("Bolognese")) _ 
     .ToDictionary(Function(x) x.Key, Function(x) x.Value) 

要獲得包含「Bolognese」的所有條目的價格列表:

Dim pricesForAllThingsBolognese = PriceList _ 
     .Where(Function(x) x.Key.Contains("Bolognese")) _ 
     .Select(Function(x) x.Value) _ 
     .ToList() 
+0

非常感謝UCH!我怎樣才能得到「博洛尼亞」的價值(在這種情況下的價格)? – PeterCo

+0

@PeterCo查看最新的答案。 –

+0

再次感謝!第三個例子很完美!第二個示例給出了類似_Overload解析失敗的內容,因爲沒有可訪問的'ToDictionary'接受這個類型arguments_。如果我將其更改爲Dim subsetOfDictionary As Dictionary(Of String,KeyValuePair(Of String,Double))= PriceList_Word(__) x)x.Key)它也能正常工作。 – PeterCo