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

Pet*_*rCo 4 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
Run Code Online (Sandbox Code Playgroud)

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

Den*_*aub 8

您可以检查是否有任何条目包含"Bolognese"使用的密钥 Any()

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

要仅使用包含"Bolognese"的键获取字典的子集:

Dim subsetOfDictionary = PriceList _ 
        .Where(Function(x) x.Key.Contains("Bolognese")) _ 
        .ToDictionary(Function(x) x.Key, Function(x) x.Value)
Run Code Online (Sandbox Code Playgroud)

要获取包含"Bolognese"的所有条目的价格列表:

Dim pricesForAllThingsBolognese = PriceList _
        .Where(Function(x) x.Key.Contains("Bolognese")) _
        .Select(Function(x) x.Value) _
        .ToList()
Run Code Online (Sandbox Code Playgroud)