When I initialize a new dictionary can I specify the key/value pairs on the same line? Thanks...
Printable View
When I initialize a new dictionary can I specify the key/value pairs on the same line? Thanks...
you can with LINQ
can you post an example?
ok. but where are you getting the data to put in the dictionary from?
Collection Initializers Overview covers all of the cases.
From the "VB can't do anything without introducing extra keywords" department:
Code:Dim lookup = New Dictionary(Of Integer, String) From {{1, "One"}, {2, "Two"}}
Yes, that's what I was looking for. Thanks!
that works great in .net4, but in .net3.5:
vb Code:
Dim items(,) As Object = {{1, "Home"}, _ {2, "Products"}, _ {3, "News"}, _ {4, "Contact Us"}} Dim d As Dictionary(Of Integer, String) = Enumerable.Range(0, items.GetLength(0)).Select(Function(i) _ New With { _ .int = CInt(items(i, 0)), _ .str = items(i, 1).ToString}).ToDictionary(Function(kvp) kvp.int, Function(kvp) kvp.str)
I think .paul. just proved that in 3.5 the answer is "No, just call Add afterwards".
With Infer On, it's the same thing. This is one of those cases where I have no objection to Infer being set to on, since Lookup can only ever be a dictionary.
-tg
Yeah, I used to hate type inference and avoid it. Then I started having to work with generic collections that contain collections of generic types. Here's something I had to play with:
One can only type that so many times before wishing for simple preprocessor macros :(.Code:Dictionary(Of Foo(Of T), List(Of Foo(Of T)))
Shouldn't it have been
-tgCode:Dictionary<Foo<T>, List<Foo<T>>>