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

C#ArraysDictionary

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - 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);
}

Solution 4 - C#

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

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

Solution 5 - C#

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

Solution 6 - C#

I'll assume that the question has to do with arrays where the keys and values alternate. I ran into this problem when trying to convert redis protocol to a dictionary.

private Dictionary<T, T> ListToDictionary<T>(IEnumerable<T> a)
{
	var keys = a.Where((s, i) => i % 2 == 0);
	var values = a.Where((s, i) => i % 2 == 1);
	return keys
		.Zip(values, (k, v) => new KeyValuePair<T, T>(k, v))
		.ToDictionary(kv => kv.Key, kv => kv.Value);
}

Solution 7 - C#

            Dictionary<int, string> dictionaryTest = new Dictionary<int, string>();

            for (int i = 0; i < testArray.Length; i++)
            {
                dictionaryTest.Add(i, testArray[i]);
            }

            foreach (KeyValuePair<int, string> item in dictionaryTest)
            {
                
                
                Console.WriteLine("Array Position {0} and Position Value {1}",item.Key,item.Value.ToString()); 
            }

Solution 8 - C#

The Question is not very clear, but Yes you can convert a string to Dictionary provided the string is delimited with some characters to support Dictionary<Key,Value> pair

So if a string is like a=first;b=second;c=third;d=fourth you can split it first based on ; then on = to create a Dictionary<string,string> the below extension method does the same

public static Dictionary<string, string> ToDictionary(this string stringData, char propertyDelimiter = ';', char keyValueDelimiter = '=')
{
    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
    Array.ForEach<string>(stringData.Split(propertyDelimiter), s =>
        {
            if(s != null && s.Length != 0)
                keyValuePairs.Add(s.Split(keyValueDelimiter)[0], s.Split(keyValueDelimiter)[1]);
        });

    return keyValuePairs;
}

and can use it like

var myDictionary = "a=first;b=second;c=third;d=fourth".ToDictionary();

since the default parameter is ; & = for the extension method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Ronald WildenbergView Answer on Stackoverflow
Solution 3 - C#shA.tView Answer on Stackoverflow
Solution 4 - C#KobiView Answer on Stackoverflow
Solution 5 - C#Andrew BullockView Answer on Stackoverflow
Solution 6 - C#Bill StantonView Answer on Stackoverflow
Solution 7 - C#DwizzleView Answer on Stackoverflow
Solution 8 - C#Vinod SrivastavView Answer on Stackoverflow