Convert List of KeyValuePair into IDictionary "C#"
Asked Answered
S

4

57

My scenario,

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

Sheerlegs answered 26/10, 2010 at 9:26 Comment(0)
A
105

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?

Astred answered 26/10, 2010 at 9:29 Comment(0)
R
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);
    } 
}
Rear answered 30/5, 2014 at 11:58 Comment(0)
N
2

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.

Naxos answered 14/1, 2022 at 9:30 Comment(2)
This seems the cleanest solution? Because I think that the extension method ToDictionary recreates the KeyValuePairsSuccession
I believe it's a bit faster, as there is some optimization done for when the dictionary is created from a list: source.dot.net/#System.Private.CoreLib/src/libraries/…Naxos
S
1

Use ToDictionary() extension method of the Enumerable class.

Scrabble answered 26/10, 2010 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.