Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 623
Robert Harvey Avatar asked Apr 06 '11 22:04

Robert Harvey


1 Answers

Get the duplicate keys:

var duplicateKeys =   myCollection  .GroupBy(k => k.Key)  .Where(g => g.Count() > 1)  .Select(g => g.Key); 
like image 179
Guffa Avatar answered Oct 02 '22 00:10

Guffa