How to get the duplicate key in a ToDictionary cast?
.net, c#, collections
Solution
You can use LINQ to catch the duplicates. You can then process them as you wish.
create a dictionary that doesn't contain the duplicates
var duplicates = myList.GroupBy(x => x.SomeKey).Where(x => x.Count() > 1);
var dictionaryWithoutDups = myList
.Except(duplicates.SelectMany(x => x))
.ToDictionary(x => x.SomeKey);
create a dictionary that contains only the first of each duplicate
var groups = myList.GroupBy(x => x.SomeKey);
var dictionaryWithFirsts = groups.Select(x => x.First()).ToDictionary(x => x.SomeKey);
Problem
i have to cast a list to a dictionary in my app but im getting an error saying that "An item with the same key has already been added". But it is a list with more then 5k objects and i need to see wich objects are with the same key. Is there a way to do that? In the message exception i cant get it, so i thought that i can do it using a foreach or something. Any suggestions? Thanks! EDIT: ``` var targetDictionary = targetCollection.ToDictionary(k => k.Key); ``` This target collection is a generic IEnumerable, and the key i get from a thirdy party database so i do not have access to it. The solution is find the problematic object and tells the supplier about it.