开发者

VB.NET and linQ: How to delete entries from a dictionary using the value

开发者 https://www.devze.com 2023-01-03 03:11 出处:网络
I have a dictionary collection as bleow: mydic.add开发者_C百科value(key1, val1) mydic.addvalue(key2, val1)

I have a dictionary collection as bleow:

mydic.add开发者_C百科value(key1, val1)
mydic.addvalue(key2, val1)
mydic.addvalue(key3, val1)
mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)

From the above dictionary I want to delete all the entries where value == "val1", so that the result would have only following entry:

mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)

My VB source code is on VS2008 and targeted for 3.5


Sub RemoveByValue(Of TKey, TValue)(ByVal dictionary As Dictionary(Of TKey, TValue), ByVal someValue As TValue)

    Dim itemsToRemove = (From pair In dictionary _
                        Where pair.Value.Equals(someValue) _
                        Select pair.Key).ToArray()

    For Each item As TKey In itemsToRemove
        dictionary.Remove(item)
    Next

End Sub

Usage:

Dim dictionary As New Dictionary(Of Int32, String)
dictionary.Add(1, "foo")
dictionary.Add(2, "foo")
dictionary.Add(3, "bar")

RemoveByValue(dictionary, "foo")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号