Linq: The Missing ToDictionary Extension Method Overload

Enumerating over a Dictionary<TKey, TValue> you will get structs of type KeyValuePair<TKey, TValue>. Whenever you use the ToDictionary extension method, you are forced to specify how to get the key and value for each item, even if it’s an enumeration of KeyValuePairs. Seems a bit redundant, doesn’t it?

public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> enumeration)
{
// Check to see that enumeration is not null
if (enumeration == null)
throw new ArgumentNullException("enumeration");
return enumeration.ToDictionary(item => item.Key, item => item.Value);
}

Well, that little bit of code settles that. :)

Advertisements

One thought on “Linq: The Missing ToDictionary Extension Method Overload

  1. For extension methods, doesn’t it make more sense to throw a NullReferenceException instead of an ArgumentNullException?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s