2012-12-13 43 views
1

在我的應用程序中,我訪問了許多不同類型的公司,例如TypeA,TypeB和TypeC。所以我有一個公司類,繼承自公司TypeA,TypeB,TypeC。C#繼承問題與集合

因此,我有一個觀點,用戶想要在TypeA上進行搜索。搜索字段包括公司中的字段和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篩選器。

+0

這不是很清楚。你可以發佈僞代碼,顯示你正在嘗試做什麼? – Oded

+0

爲什麼你需要先做一個呢? – cjk

+0

不知道答案,但對於其他人,我認爲他想要做的是找到一種方法來過濾基於他的基類中的字段的集合,然後再對他的繼承類應用篩選器 – Sayse

回答

4

可以使用LINQOfType<T>()方法進行預過濾Company對象的列表,併產生IEnumerable<TypeA>,像這樣:

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

可以在後續LINQ過濾器中使用的TypeA性質 - 下面的代碼將工作,即使Property1僅適用於TypeA而不是在Company

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

看起來很有用,我會試試看。 – arame3333