【问题标题】:How to get an object with certain type using C# Linq?如何使用 C# Linq 获取特定类型的对象?
【发布时间】:2012-09-09 16:51:45
【问题描述】:

我有持有根对象的通用列表意味着我有:

public class Component  
{  
}  

public class DBComponent : Component  
{  
}  

private List<Component> components;   

我想使用 Linq 获取仅包含 DBComponent 引用的列表。意思是这样的:

List<DBComponent> dbComponents = components.FindAll(c => c is DBComponent);  

但是,它似乎不起作用
请问有人可以提供有效的 Linq 代码吗?
谢谢

【问题讨论】:

  • 为什么不起作用?会发生什么?

标签: c# linq generics inheritance polymorphism


【解决方案1】:

你在寻找

IEnumerable<DBComponent> dbComponents = components.OfType<DBComponent>();

【讨论】:

    【解决方案2】:
    List<DBComponent> dbComponents = components.OfType<DBComponent>().ToList();
    

    【讨论】:

    • 关键是他想要一个包含超类类型对象的列表中的 DBComponents 列表。
    • 我的意思是,单元测试的重点。只是一堆噪音掩盖了你的真实答案,即components.OfType&lt;DBComponent&gt;().ToList()
    • 其实,你说得对 minitech .. .. 正要删除我的答案,但它实际上是正确的答案,因为 liorafar 想要它作为一个列表。感谢您提出您的观点。
    【解决方案3】:

    可能是这样的,即使您的代码似乎也是有效的。

    var result = components.Where(c => (c as DBComponent)!=null)
    

    【讨论】:

      【解决方案4】:
      components.OfType<DBComponent>();
      

      【讨论】:

        【解决方案5】:

        您应该使用OfTypeCast 方法。关键区别在于Cast 抛出异常,如果 Enumerable 包含任何无法转换为目标类型的元素。 OfType 不会抛出此异常,而只是跳过这些类型的元素。

        在不同的情况下,这两种方法都可以派上用场,因此您可以自行选择。如果您只想按某种类型过滤您的 Enumerable,我猜OfType 就是您所需要的。

        【讨论】:

          猜你喜欢
          • 2013-01-20
          • 2022-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多