[英]How to delete an item from a Dictonary using LINQ in C#
I need to delete a specific item from a dictonary.. 我需要从字典中删除特定项目。
The dictonary is like 字典像
dict["Key1"]="Value1"
dict["Key2"]="Value2"
dict["Key3"]="Value3"
dict["Key4"]="Value2"
How to delete the item if another item has the same value using LINQ 如果另一个项目使用LINQ具有相同的值,如何删除该项目
Thanks in advance 提前致谢
check orginal answer by @Jon Skeet : C#: Remove duplicate values from dictionary? 通过@Jon Skeet检查原始答案: C#:从字典中删除重复的值?
var uniqueValues = myDict.GroupBy(pair => pair.Value)
.Select(group => group.First())
.ToDictionary(pair => pair.Key, pair => pair.Value);
Here my tested solution: 这是我测试过的解决方案:
dict.GroupBy(x => x.Value, x => x.Key)
.Where(x => x.Count() > 1)
.SelectMany(x => x.Skip(1))
.ToList().ForEach(x => dict.Remove(x))
var dupKeys = dict.GroupBy(innerD => innerD.Value)
.Where(mergedByValue => mergedByValue.Count() > 1)
.Select(mergedByValue => mergedByValue.OrderByDescending(m => m.Key).First().Key);
dict.Where(d => dupKeys.Contains(d.Key)).ToList()
.ForEach(d => dict.Remove(d.Key));
This assumes you want the last duplicate removed, where last is defined as the last ordinal string value. 假设您要删除最后一个重复项,其中last被定义为最后一个序数字符串值。
If you want all duplicates removed, change your dupKeys to this: 如果要删除所有重复项,请将dupKeys更改为此:
var dupKeys = dict.GroupBy(innerD => innerD.Value)
.Where(mergedByValue => mergedByValue.Count() > 1).Dump()
.SelectMany(mergedByValue => mergedByValue.Select(m => m.Key));
您需要使用Distinct 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.