开发者

Convert List of KeyValuePair into IDictionary "C#"

My scenario,

how to convert L开发者_开发技巧ist<KeyValuePair<string, string>> into IDictionary<string, string>?


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?


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


Use ToDictionary() extension method of the Enumerable class.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜