由网友(|放生∮Melody)分享简介:如何从词典中删除所有重复使用LINQ的声明看起来像这样:How to remove all duplicates with a LINQ statement from a dictionary looking like this:Dictionary()2型包含字符串属性ID。我想删除具...
如何从词典中删除所有重复使用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)
;
相关推荐
最新文章