I have a string array with strings and a dictionary.
String [] str_array;
Dictionary<int, string> dict = new Dictionary<int, string>();
dict = str_array.toDictionary();
How do I get my array into a dictionary with int and String?
I have seen all those examples with bool, but I need int and string.
The int (key) would be just the actual position of the dictionary (dict.count) and the value would be the value of the array at that position.
edit: thx to all answers but I do not want to iterate over array. I assume that with array.toDictionary the performance would be better than iterating over array and just assigning the value of the array to a dictionary. Arrays might have 5k elements.
edit2: the reason is that i have to pass a dictionary to a method…its REQUIRED. and all my values are within a simple array.
edit3: The most important thing is performance. Maybe iterating over array and assigning values to dict is faster than array.toDictionary, but the problem is that i do not have that little piece of code to benchmark both.
First – your problem over performance is interesting and smacks of premature optimisation – as this answer will show, you’re probably looking at a couple of milliseconds difference in performance between a
forloop andToDictionary.Unless you are running this in a realtime system I can’t see much of a problem.
On to the show – the following is a crude benchmark (only real-world timings are reliable) of three (and a half) different ways I can think of to build the dictionary. The first uses the
forloop, with the second doing the same but not using the array’sLengthproperty (just for interest); the third and fourth useToDictionary; one uses aSelectand one uses a counter variable (a hybrid):Results (Release build, and takes about 20 seconds to run on my Dell 2.4Ghz Workstation):
So
forloop is undeniably faster – by at least 22% of the closestToDictionaryimplementation. I’ve tried it with 100,000 elements and it gets up to about 30% then.Note the second
forloop result – seems to suggest that bypassing theLengthproperty is a good idea. Indeed I’ve done 4 runs in a row and these are the results (including the first, from above):However I have seen the results flip for at least one benchmark result, too – demonstrating how largely pointless this kind of benchmarking can be. Realistically we should be generating a different array for each test, too, to avoid caching etc.
There is an alternative.
If the method you’re calling accepts an
IDictionary<int, string>(note – the interface); and not aDictionary<int, string>you can create a simple wrapper type that implements the necessary members of the interface, thus sidestepping the need to project into a Dictionary at all; so long as only certain members are required. Here’s an almost complete implementation: