如何从 KeyValuePair 列表中返回具有特定值的所有键(vb.net 或 C#)
给定以下 vb.net 类:
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
函数 FindByValue 返回适合某个值的单个 KeyValuePair。但是,此 PairCollection 的实现可能具有 m:1 个键值对,因此我希望返回具有该值(可能有多个)的所有键(并且仅键)。
我对 vb.net 中的 Lambda 表达式很陌生,而且对 C# 更熟悉,但问题并没有变得更容易。我可以编写一个简单的例程来迭代集合,但我觉得有一个 lambda & 。通用组合方法。
我认为我正在尝试做的是以下内容:
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
我正在尝试的背后的相关推理是 此处。
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 fits 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你做得正确。您只需使用
Select
投影输出即可。顺便说一句,继承
List
几乎总是错误的做法。尝试重新设计你的班级。You are doing it correctly. You just need to project the output with
Select
.By the way, inheriting
List
is almost always a wrong thing to do. Try redesigning your class.