开发者

VB.NET (or C#) creating a Dictionary from an existing List without looping

开发者 https://www.devze.com 2023-04-01 05:31 出处:网络
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

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.

0

精彩评论

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