从.NET词典中删除与谓词匹配的多个项目的最佳方法? [英] Best way to remove multiple items matching a predicate from a .NET Dictionary?
问题描述
我需要从字典中删除多个项目.一种简单的方法如下:
I need to remove multiple items from a Dictionary. A simple way to do that is as follows :
List<string> keystoremove= new List<string>();
foreach (KeyValuePair<string,object> k in MyCollection)
if (k.Value.Member==foo)
keystoremove.Add(k.Key);
foreach (string s in keystoremove)
MyCollection.Remove(s);
我不能直接删除foreach块中的项目的原因是,这将引发异常(集合已修改...")
The reason why I can't directly Remove the items in the foreach block is that this would throw an Exception ("Collection was modified...")
我想执行以下操作:
MyCollection.RemoveAll(x =>x.Member==foo)
但是Dictionary<>类没有像List<>类那样公开RemoveRemoveAll(Predicate<> Match)方法.
But the Dictionary<> class doesn't expose a RemoveAll(Predicate<> Match) method, like the List<> Class does.
做到这一点的最佳方法是什么(无论是性能方面还是优雅方面)?
What's the best way (both performance wise and elegant wise) to do that?
推荐答案
这是另一种方法
foreach ( var s in MyCollection.Where(kv => kv.Value.Member == foo).ToList() ) {
MyCollection.Remove(s.Key);
}
直接将代码放入列表中,可以避免出现枚举时删除"问题. .ToList()
将在foreach真正开始之前强制进行枚举.
Pushing the code into a list directly allows you to avoid the "removing while enumerating" problem. The .ToList()
will force the enumeration before the foreach really starts.
这篇关于从.NET词典中删除与谓词匹配的多个项目的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!