Finding duplicate key in a List of KeyValuePair

倖福魔咒の 提交于 2020-12-11 08:59:55

问题


I have a List of Key Value pairs in my project. I would like to search that List<KeyValuePair<String,object>> and find any duplicate keys and get both that key and value using a C# lambda expressions. Does anybody know how to do that?

This is my Sample code

list = List<KeyValuePair<string, Object>>

I need to search this list and get any item(s) of KeyValuePair<string, Object> with the duplicate key(String).

Any help would be greatly appreciated


回答1:


IEnumerable<IGrouping<string, KeyValuePair<string, object>>> duplicateKVPsByKey = list.GroupBy(kvp => kvp.Key).Where(g => g.Count() > 1);

This groups the list of KVPs by key and then filters it down to only those groups of KVPs with more than 1.

From there you could loop through the list and see each duplicate key and also see the objects associated.

This will print out all the keys and the objects associated with them

foreach (var group in duplicateKVPsByKey)
{
    Console.WriteLine(group.Key);
    foreach (var kvp in group)
    {
        Console.WriteLine(kvp.Value.ToString());
    }
}


来源:https://stackoverflow.com/questions/16049614/finding-duplicate-key-in-a-list-of-keyvaluepair

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!