Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Get Firefox

Locations of visitors to this page

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

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. :)

Comments

Joe Chung said:

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

# April 22, 2008 3:19 PM

Omer van Kloeten said:

Not really.

NullReferenceExceptions are something that usually comes from the CLR. It would be wise to throw them if I couldn't call the method using both of these ways:

enumeration.ToDictionary()

ToDictionary(enumeration)

When using the latter, a NullReferenceException would just be confusing.

# April 22, 2008 3:32 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)