How to convert IEnumerable of KeyValuePair<x, y> to Dictionary?

回眸只為那壹抹淺笑 提交于 2019-12-21 06:48:34

问题


Is there streamlined way to convert list/enumberable of KeyValuePair<T, U> to Dictionary<T, U>?

Linq transformation, .ToDictionary() extension did not work.


回答1:


.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value);

Isn't that much more work.




回答2:


You can create your own extension method that would perform as you expect.

public static class KeyValuePairEnumerableExtensions
{
    public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
    {
        return source.ToDictionary(item => item.Key, item => item.Value);
    }
}



回答3:


This is the best I could produce:

public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
{
    var dict = new Dictionary<TKey, TValue>();
    var dictAsIDictionary = (IDictionary<TKey, TValue>) dict;
    foreach (var property in keyValuePairs)
    {
        (dictAsIDictionary).Add(property);
    }
    return dict;
}

I compared the speed of converting an IEnumerable of 20 million key value pairs to a Dictionary using Linq.ToDictionary with the speed of this one. This one ran in 80% of the time of the Linq version. So it's faster, but not a lot. I think you'd really need to value that 20% saving to make it worth using.



来源:https://stackoverflow.com/questions/7850334/how-to-convert-ienumerable-of-keyvaluepairx-y-to-dictionary

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