好的,我有一系列基于基类的对象,这些对象随机存储在 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 <long, TypeA>;
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);
}
关于c# - 在字典中选择特定对象类型并将其删除的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1064301/