将KeyValuePair列表转换为IDictionary"C#"

anb*_*van 39 c# idictionary

我的情景,

怎么转换List<KeyValuePair<string, string>>IDictionary<string, string>

Jon*_*eet 72

非常非常简单地使用LINQ:

IDictionary<string, string> dictionary =
    list.ToDictionary(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)

请注意,如果有任何重复键,这将失败 - 我认为没关系?


Кеш*_*нов 8

或者您可以使用此扩展方法来简化代码:

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);
    } 
}
Run Code Online (Sandbox Code Playgroud)