与集合有关的 C# 继承问题

标签 c#

在我的应用程序中,我访问了许多不同类型的公司,比如 TypeA、TypeB 和 TypeC。所以我有一个 company 类,从 Company 继承的是 TypeA、TypeB、TypeC。

所以我有一个 View ,用户想要在 TypeA 上进行搜索。搜索字段包括Company中的字段和TypeA中的字段。 但是,如果我有一个 TypeA 集合,比如 IEnumberable,在 TypeA 类中过滤它们之前,如何过滤 Company 类中的字段?

编辑

这是我的伪代码

public abstract class Company
{
      public string Property1 { get; set; }
      public string Property2 { get; set; }

}

public class TypeA : Company
{
      public string Property3 {get; set; }
}

public class TypeB : Company
{
      public string Property4 {get; set; }
}

public abstract class SearchCompany
{
      protected SearchCompany(string searchpProperty1, string searchProperty2)
      {
           // assign property code elided
      }

      public string SearchProperty1 { get; set; }
      public string SearchProperty2 { get; set; }

}

public class SearchTypeA : SearchCompany
{
      public SearchTypeA (string searchpProperty1, string searchProperty2, string searchProperty3)
           : base (searchpProperty1, searchProperty2)
      {
          // assign property code elided
          this.TypeAList = CacheObjects.TypeAList;
          this.TypeAList = // this.TypeAList filtered by searchProperty3 depending on the wildcard
      }

      public string SearchProperty3 { get; set; }
      public IList<TypeA> TypeAList { get; set; }
}

我也想过滤属性 1 和 2。

最佳答案

您可以使用 LINQOfType<T>()预过滤 Company 列表的方法对象,并产生IEnumerable<TypeA> ,像这样:

IEnumerable<TypeA> typeA = allCompanies.OfType<TypeA>();

您可以使用 TypeA 的属性在随后的 LINQ 过滤器中 - 即使 Property1,下面的代码也能正常工作仅适用于 TypeA而不是在 Company 上:

var filteredTypeA = typeA.Where(c => c.Property1 = "xyz").ToList();

关于与集合有关的 C# 继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13858788/

相关文章:

c# - 错误消息 'The specified locale is not supported on this operating system.'

c# - 如何优化这些空值检查操作?

c# - 当不抛出异常时,try/catch block 会影响性能吗?

c# - 目标框架是如何工作的(以及为什么 2.0 的 lib 可以使用 4.0 的 lib)?

c# - : Conversion operators cannot convert from an interface type如何解决

c# - 将 List<string> 转换为 IEnumerator<string>

c# - 冲洗 System.Console.Read()

c# - 无法反转整数数组

c# - 我如何在 XNA 中获取和设置像素数据?

c# - 是否支持在 .Net Framework 中使用 C# 的 POP3 客户端?