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?


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

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

IMO, When we say an Array we are talking about a list of values that we can get a value with calling its index (value => array[index]), So a correct dictionary is a dictionary with a key of index.

And with thanks to @John Skeet, the proper way to achieve that is:

var dictionary = array
    .Select((v, i) => new {Key = i, Value = v})
    .ToDictionary(o => o.Key, o => o.Value);

Another way is to use an extension method like this:

public static Dictionary<int, T> ToDictionary<T>(this IEnumerable<T> array)
{
    return array
        .Select((v, i) => new {Key = i, Value = v})
        .ToDictionary(o => o.Key, o => o.Value);
}

If you need a dictionary without values, you might need a HashSet:

var hashset = new HashSet<string>(stringsArray);

What do you mean?

A dictionary is a hash, where keys map to values.

What are your keys and what are your values?

foreach(var entry in myStringArray)
    myDictionary.Add(????, entry);