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 LINQ Distinct
method prior to calling ToDictionary
.
var dict = myCollection.Distinct().ToDictionary(x => x.Key);
Of course, the above will only work if the classes in your collection override Equals
and GetHashCode
in a way that only takes the Key
property into account. If that's not the case, you'll need to make a custom IEqualityComparer<YourClass>
that only compares the Key
property.
var comparer = new MyClassKeyComparer();
var dict = myCollection.Distinct(comparer).ToDictionary(x => x.Key);
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.