有人可以告诉我,如何只搜索字典中的一部分键(在VB.NET中)? 我使用以下示例代码: Dim PriceList As New Dictionary(Of String, Double)(System.StringComparer.OrdinalIgnoreCase) PriceList.Add("Spaghetti alla carbonar
我使用以下示例代码:
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
如果我只知道像“Bolognese”这样的关键部分,或者只是像“Bolo”这样的单词的一部分,那么如何在完整的密钥中搜索这部分?
您可以使用Any()检查是否有任何包含“Bolognese”的键的条目If Not PriceList.Where(Function(x) x.Key.Contains("Bolognese")).Any()
Console.WriteLine("No Bolognese, sorry")
End If
要仅使用包含“Bolognese”的键获取字典的子集:
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()
