Convert List of KeyValuePair into IDictionary “C#”

ぃ、小莉子 提交于 2019-12-18 12:45:33

问题


My scenario,

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


回答1:


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?




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



回答3:


Use ToDictionary() extension method of the Enumerable class.



来源:https://stackoverflow.com/questions/4022304/convert-list-of-keyvaluepair-into-idictionary-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!