56

My scenario,

how to convert List<KeyValuePair<string, string>> into IDictionary<string, string>?

holmis83
  • 15,922
  • 5
  • 82
  • 83
anbuselvan
  • 1,201
  • 4
  • 16
  • 21

4 Answers4

103

Very, very simply with LINQ:

IDictionary<string, string> dictionary =
    list.ToDictionary(pair => pair.Key, pair => pair.Value);

Note that this will fail if there are any duplicate keys - I assume that's okay?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
8

Or you can use this extension method to simplify your code:

public static class Extensions
{
    public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(
        this IEnumerable<KeyValuePair<TKey, TValue>> list)
    {
            return list.ToDictionary(x => x.Key, x => x.Value);
    } 
}
1

Use ToDictionary() extension method of the Enumerable class.

Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
1

You can also use the constructor overload of Dictionary<TKey,TValue> that takes an IEnumerable<KeyValuePair<TKey,TValue>> as parameter.

var list = new List<KeyValuePair<int, string>>();
var dictionary = new Dictionary<int, string>(list);
colinD
  • 1,641
  • 1
  • 20
  • 22