Alex Rivera | Logout

How do you get the duplicate key that ToDictionary() has failed on?

Asked 2011-04-06T22:25:59.210
23

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?

Edit
Report

2 Answers

18

Get the duplicate keys:

var duplicateKeys =
  myCollection
 .GroupBy(k => k.Key)
 .Where(g => g.Count() > 1)
 .Select(g => g.Key);
answered 2011-04-06T22:28:47.167
10

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.

answered 2011-04-06T22:46:28.173

Your Answer