c# - 在字典中选择特定对象类型并将其删除的最有效方法

标签 c# linq collections

好的,我有一系列基于基类的对象,这些对象随机存储在 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/

相关文章:

c# - 如何在Azure blob存储中保留空目录?

c# - FTP 上传失败 'The underlying connection was closed: An unexpected error occurred on a receive.'

c# - 在LINQ查询中,调用ToDictionary时,为键和值分配了什么?

c# - 如何使用 LINQ SQL 连接根据 ID 连接 3 个表? C# MVC(.NET Core 2.0)

Java PriorityQueue initElementsFromCollection 方法

c# - 使用 Func<> 的 FindBy 方法的 Moq 存储库设置

c# - 自定义 ModelBinder 不适用于 Nullable 类型

c# - linq query Take() 优先于 Distinct()?

java - hamcrest containsInAnyOrder 仅适用于特定订单

c# - 这样的集合是否存在(Dictionary 和 HashSet 的功能)?