3

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

Necrolyte2
  • 738
  • 5
  • 13
dotnetdev_2009
  • 722
  • 1
  • 11
  • 28

1 Answers1

7
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());
    }
}
rclement
  • 1,664
  • 14
  • 10