Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to convert string array into a dictionary of strings

Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?

like image 246
leora Avatar asked Sep 06 '09 11:09

leora


People also ask

How do I convert a string to a dictionary?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.

Which is faster array or dictionary?

If you are going to get elements by positions (index) in the array then array will be quicker (or at least not slower than dictionary). If you are going to search for elements in the array than dictionary will be faster.


2 Answers

Assuming you're using .NET 3.5, you can turn any sequence (i.e. IEnumerable<T>) into a dictionary:

var dictionary = sequence.ToDictionary(item => item.Key,                                        item => item.Value) 

where Key and Value are the appropriate properties you want to act as the key and value. You can specify just one projection which is used for the key, if the item itself is the value you want.

So for example, if you wanted to map the upper case version of each string to the original, you could use:

var dictionary = strings.ToDictionary(x => x.ToUpper()); 

In your case, what do you want the keys and values to be?

If you actually just want a set (which you can check to see if it contains a particular string, for example), you can use:

var words = new HashSet<string>(listOfStrings); 
like image 150
Jon Skeet Avatar answered Sep 25 '22 21:09

Jon Skeet


You can use LINQ to do this, but the question that Andrew asks should be answered first (what are your keys and values):

using System.Linq;  string[] myArray = new[] { "A", "B", "C" }; myArray.ToDictionary(key => key, value => value); 

The result is a dictionary like this:

A -> A B -> B C -> C 
like image 27
Ronald Wildenberg Avatar answered Sep 26 '22 21:09

Ronald Wildenberg