在我的应用程序中,我访问了许多不同类型的公司,比如 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。
最佳答案
您可以使用 LINQ
的 OfType<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/