在KeyValuePair列表中查找重复的键 [英] Finding duplicate key in a List of KeyValuePair

查看:89
本文介绍了在KeyValuePair列表中查找重复的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一个键值对列表.我想搜索该List<KeyValuePair<String,object>>并找到任何重复的键,并使用C#lambda表达式获取该键和值.有人知道怎么做吗?

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?

这是我的示例代码

list = List<KeyValuePair<string, Object>>

我需要搜索此列表,并使用重复的键(字符串)获取KeyValuePair<string, Object>的任何项目.

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

任何帮助将不胜感激

推荐答案

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

这将按键对KVP列表进行分组,然后将其筛选为仅包含1个以上KVP的组.

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());
    }
}

这篇关于在KeyValuePair列表中查找重复的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆