C# Convert List<string> to Dictionary<string, string>

Jonnster picture Jonnster · Jul 20, 2012 · Viewed 196.1k times · Source

This may seem an odd thing to want to do but ignoring that, is there a nice concise way of converting a List to Dictionary where each Key Value Pair in the Dictionary is just each string in the List. i.e.

List = string1, string2, string3
Dictionary = string1/string1, string2/string2, string3/string3

I have done plenty of searching and there are literally dozens of examples on Stackoverflow alone of doing it in the opposite direction but not this way round.

The reason for doing this is I have two third part components and changing them is out of my hands. One returns a list of email addresses as a List and the other sends emails where the To parameter is a Dictionary. The key of the dictionary is the email address and the value is their real name. However, I don't know the real name but it still works if you set the real name to the email address as well. Therefore why I want to convert a List to a Dictionary. There are plenty of ways of doing this. A foreach loop on the list which adds a kvp to a dictionary. But I like terse code and wondered if there was a single line solution.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jul 20, 2012

Try this:

var res = list.ToDictionary(x => x, x => x);

The first lambda lets you pick the key, the second one picks the value.

You can play with it and make values differ from the keys, like this:

var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));

If your list contains duplicates, add Distinct() like this:

var res = list.Distinct().ToDictionary(x => x, x => x);

EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String> would provide a much better fit for your situation:

var res = new HashSet<string>(list);
if (res.Contains("string1")) ...