3

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?

vulkanino
  • 9,074
  • 7
  • 44
  • 71

3 Answers3

7

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).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
2

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)

xanatos
  • 109,618
  • 12
  • 197
  • 280