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 开发者_JAVA技巧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?
This purpose is fulfilled by the ToDictionary
extension method:
Dim result = myList.ToDictionary(Function (x) x.key, Function (x) x.description)
Even if this is doable, internally it will loop through all the List items, I guess?
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).
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 is myCollection.ToDictionary(Function(p) p.key)
Yes, it will loop through all the list items. Another thing you can do is create a KeyedCollection for your list:
public class MyTypeCollection : KeyedCollection<char, MyType>
{
protected override char GetKeyForItem(MyType item)
{
return item.key;
}
}
but that won't help you adding the items.
精彩评论