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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17998321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:29:55  来源:igfitidea点击:

How to search for a part of a dictionary key?

vb.netdictionarystring-matching

提问by PeterCo

Could someone please tell me, how I can search for only a part of a key in a dictionary (in VB.NET)?

有人可以告诉我,我如何才能在字典(在 VB.NET 中)中只搜索键的一部分?

I use the following sample code:

我使用以下示例代码:

    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

If I only know a part of the key like "Bolognese" or just a part of word like "Bolo", how can I search for this part in the complete key?

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

回答by Dennis Traub

You can check if there's any entry which a key containing "Bolognese" using Any()

您可以检查是否有任何条目使用包含“Bolognese”的键 Any()

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

To get a subset of the dictionary with keys containing "Bolognese" only:

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

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

To get the list of prices for all entries containing "Bolognese":

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

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