如何在ToDictionary演员表中获取重复键?

gog*_*gog 2 .net c# collections

我必须在我的应用程序中将一个列表转换为字典,但我得到一个错误,说"已经添加了具有相同键的项目".但它是一个包含超过5k对象的列表,我需要看到具有相同键的对象.有没有办法做到这一点?在消息异常中,我无法得到它,所以我认为我可以使用foreach或其他东西.有什么建议?谢谢!

编辑:

   var targetDictionary = targetCollection.ToDictionary(k => k.Key);
Run Code Online (Sandbox Code Playgroud)

这个目标集合是一个通用的IEnumerable,我从第三方数据库获得的密钥,所以我无法访问它.解决方案是找到有问题的对象并告诉供应商.

Nat*_*n A 7

您可以使用LINQ来捕获重复项.然后,您可以根据需要处理它们.

创建一个不包含重复项的字典

var duplicates = myList.GroupBy(x => x.SomeKey).Where(x => x.Count() > 1);

var dictionaryWithoutDups = myList
    .Except(duplicates.SelectMany(x => x))
    .ToDictionary(x => x.SomeKey);
Run Code Online (Sandbox Code Playgroud)

创建一个只包含每个副本中第一个的字典

var groups = myList.GroupBy(x => x.SomeKey);

var dictionaryWithFirsts = groups.Select(x => x.First()).ToDictionary(x => x.SomeKey);
Run Code Online (Sandbox Code Playgroud)