I'm creating a Dictionary object, using IEnumerable
's ToDictionary()
extension method:
var dictionary = new Dictionary<string, MyType>
(myCollection.ToDictionary<MyType, string>(k => k.Key));
When it executes, it throws the following ArgumentException
:
An item with the same key has already been added.
How do I get it to tell me what the duplicate key is?
The
ArgumentException
being thrown by the call toDictionary.Add
doesn't contain the key value. You could very easily add the entries to a dictionary yourself, and do a distinct check beforehand:This extra check should be fairly inexpensive because elements are stored by hash.
If your specific situation makes it okay to only insert one of a set of objects with duplicate
Key
properties into your dictionary, you can avoid this error entirely by using the LINQDistinct
method prior to callingToDictionary
.Of course, the above will only work if the classes in your collection override
Equals
andGetHashCode
in a way that only takes theKey
property into account. If that's not the case, you'll need to make a customIEqualityComparer<YourClass>
that only compares theKey
property.If you need to make sure that all instances in your collection end up in the dictionary, then using
Distinct
won't work for you.The failed key is not included because the generic dictionary has no guarantee that there is a meaningful ToString method on the key type. You could create a wrapper class that throws a more informative exception. For example:
Get the duplicate keys: