从与对象字典中删除重复的基础上,该值的属性 [英] Remove duplicates from a dictionary with object, based on a property in the Value

查看:144
本文介绍了从与对象字典中删除重复的基础上,该值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从词典中删除所有重复使用LINQ的声明看起来像这样:

How to remove all duplicates with a LINQ statement from a dictionary looking like this:

Dictionary<Type1, Type2>()

2型包含字符串属性ID。我想删除具有相同ID的所有条目

Type2 contains a string property ID. I want to remove all entries that has the same ID

推荐答案

可以组要和特定领域的字典中,然后拿到的第一个值匹配(或全部):

You can group the dictionary on a specific field you want to, and then get the first value matching (or all):

Dictionary<Type1, Type2> d = new Dictionary<Type1, Type2>();

var entriesToBeRemoved = d.GroupBy(x => x.Value.SomeId)
                         .SelectMany(x => x.Skip(1))
                         .ToList()
                         ;

foreach (var kvp in entriesToBeRemoved)
{
    d.Remove(kvp.Key);
}

或者,如果你不小心创造结果的新词典:

Or if you don't care to create a new dictionary for the results:

Dictionary<Type1, Type2> d = new Dictionary<Type1, Type2>();

var d2 = d.GroupBy(x => x.Value.SomeId)
          .ToDictionary(x => x.First().Key, x => x.First().Value)
          ;

这篇关于从与对象字典中删除重复的基础上,该值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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