好吧,我有一系列基于基类的对象,这些对象随机存储在Dictionary对象中.例如
class TypeA { public int SomeNumber {get; set;} public void SomeFunction() } class TypeB : TypeA { public string SomeString {get; set;} } class TypeC : TypeA { public bool StuffReady() } Dictionary listOfClasses;
Key值是已放入字典的对象数的运行计数.它与当前字典计数不匹配.
我希望找到TypeB的一个对象,其SomeString =="123"说,并删除它.这样做的最佳方式是什么?
如果您确定只有一个匹配的对象(或者您只想删除第一个匹配项):
var found = listOfClasses.FirstOrDefault ( x => (x.Value is TypeB) && (((TypeB)x.Value).SomeString == "123") ); if (found.Value != null) { listOfClasses.Remove(found.Key); }
如果可能有多个匹配对象,并且您想要将它们全部删除:
var query = listOfClasses.Where ( x => (x.Value is TypeB) && (((TypeB)x.Value).SomeString == "123") ); // the ToArray() call is required to force eager evaluation of the query // otherwise the runtime will throw an InvalidOperationException and // complain that we're trying to modify the collection in mid-enumeration foreach (var found in query.ToArray()) { listOfClasses.Remove(found.Key); }