从 .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);
之所以不能直接Remove foreach块中的items是因为这样会抛出异常("Collection was modified...")
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<> 类那样公开 RemoveAll(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屋!