How to convert IEnumerable of KeyValuePair to D

2019-04-03 05:44发布

问题:

Is there streamlined 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.