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

爷,独闯天下 提交于 2019-12-03 22:12:16
.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value);

Isn't that much more work.

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

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.

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