VB.NET(或 C#)从现有列表创建字典而不循环
我不知道这是否可行,也许可以使用 Linq,但我有一个 List(Of MyType)
:
Public Class MyType
Property key As Char
Property description As String
End Class
并且我想创建一个 Dictionary(Of Char, MyType)
使用键字段作为字典键,使用 List
中的值作为字典值,类似于:
New Dictionary(Of Char, MyType)(??)
即使这是可行的,我猜它在内部也会循环遍历所有列表项?
I don't know if this is doable, maybe with Linq, but I have a List(Of MyType)
:
Public Class MyType
Property key As Char
Property description As String
End Class
And I want to create a Dictionary(Of Char, MyType)
using the key field as the dictionary keys and the values in the List
as the dictionary values, with something like:
New Dictionary(Of Char, MyType)(??)
Even if this is doable, internally it will loop through all the List items, I guess?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此目的是通过
ToDictionary
扩展方法:当然。事实上,不循环的实现是可以想象的,但是会导致字典查找效率非常低(这样的实现会在现有列表上创建一个视图,而不是的副本)。这仅适用于非常非常小的词典(例如<10个项目)。
This purpose is fulfilled by the
ToDictionary
extension method:Of course. In fact, an implementation without looping is thinkable but would result in a very inefficient look-up for the dictionary (such an implementation would create a view on the existing list, instead of a copy). This is only a viable strategy for very small dictionaries (< 10 items, say).
在 C# 中,有
ToDictionary
< /a>,但是它会循环:-)您可以使用类似以下内容来调用它:
myCollection.ToDictionary(p => p.key)
。在 VB.NET 中,我认为语法是 myCollection.ToDictionary(Function(p) p.key)In C# there is the
ToDictionary<TKey, TSource>
, but yes it will loop :-)You would call it with something like:
myCollection.ToDictionary(p => p.key)
. In VB.NET I think the syntax ismyCollection.ToDictionary(Function(p) p.key)
是的,它将循环遍历所有列表项。您可以做的另一件事是为您的列表创建一个 KeyedCollection :
但是不会帮助您添加项目。
Yes, it will loop through all the list items. Another thing you can do is create a KeyedCollection for your list:
but that won't help you adding the items.