开发者

How to return all keys with a certain value from a list of KeyValuePair (vb.net or C#)

Given the following vb.net class:

Friend Class PairCollection(Of TKey, TValue)
    Inherits List(Of KeyValuePair(Of TKey, TValue))

    Public Overloads Sub Add(ByVal key As TKey, ByVal value As TValue)
        Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))
    End Sub

    Public Function FindByValue(ByVal value As TValue) As List(Of KeyValuePair(Of TKey, TValue))
        Return Me.FindAll(Function(item As KeyValuePair(Of TKey, TValue)) (item.Value.Equals(value)))
    End Function

End Class

The function FindByValue returns a single KeyValuePair that fit开发者_高级运维s a value. However, an implementation of this PairCollection might have m:1 key to value, so I wish to return all keys (and key's only) that have that value (there could be more than one).

Problem isn't made easier that I'm new to Lambda expressions in vb.net, and more familiar with C#. I could write a simple routine to iterate over the collection, but I feel there is a lambda & generic combined approach.

I think what I am trying to do is something along the lines of the following:

Public Function FindByValue2(ByVal value As TValue) As List(Of TKey)
    Return Me.FindAll(Function(item As list(of TKey) (item.Value.Equals(value)))
End Function

Related reasoning behind what I am attempting is here.


You are doing it correctly. You just need to project the output with Select.

Public Function FindByValue(ByVal value As TValue) As List(Of TKey)
    Return Me.Where(Function(item) item.Value.Equals(value)) _
             .Select(Function(x) x.Key).ToList()
End Function

By the way, inheriting List is almost always a wrong thing to do. Try redesigning your class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜