anbuselvan
anbuselvan

Reputation: 1241

Convert List of KeyValuePair into IDictionary "C#"

My scenario,

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

Upvotes: 57

Views: 30870

Answers (4)

colinD
colinD

Reputation: 2039

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

Note that an exception is thrown if the list contains one or more duplicated keys.

Upvotes: 2

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

Upvotes: 8

Andrew Bezzub
Andrew Bezzub

Reputation: 16032

Use ToDictionary() extension method of the Enumerable class.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499800

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?

Upvotes: 105

Related Questions