如何搜索字典键的一部分?

时间:2013-08-01 15:29:11

标签: vb.net dictionary string-matching

有人可以告诉我,如何只搜索字典中的一部分密钥(在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

如果我只知道像“Bolognese”这样的键的一部分,或者只是像“Bolo”这样的词的一部分,那么如何在完整的键中搜索这部分?

1 个答案:

答案 0 :(得分:7)

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