2008-10-01 57 views
28

是否可以在LINQ查詢中進行投射(爲了編譯器)?在LINQ查詢中進行投射

下面的代碼並不可怕,但它會很美好,使之成爲一個查詢:

Content content = dataStore.RootControl as Controls.Content; 

List<TabSection> tabList = (from t in content.ChildControls 
          select t).OfType<TabSection>().ToList(); 

List<Paragraph> paragraphList = (from t in tabList 
           from p in t.ChildControls 
           select p).OfType<Paragraph>().ToList(); 

List<Line> parentLineList = (from p in paragraphList 
          from pl in p.ChildControls 
          select pl).OfType<Line>().ToList(); 

代碼繼續與幾個疑問,但關鍵是我要創建一個列出每個查詢,以便編譯器知道content.ChildControls中的所有對象都是TabSection類型,並且t.ChildControls中的所有對象都是Paragraph等類型,等等。

在LINQ查詢中有沒有辦法告訴編譯器tfrom t in content.ChildControlsTabSection

回答

25

試試這個:

from TabSection t in content.ChildControls 

而且,即使這是不可用(或您可能會遇到不同的,未來的情況),你就不會被限制在一切轉換成列表。轉換爲列表會導致當場進行查詢評估。但是,如果刪除ToList調用,則可以使用IEnumerable類型,這將繼續推遲查詢的執行,直到您實際迭代或存儲在實際容器中。

1

是的,你可以做到以下幾點:

List<TabSection> tabList = (from t in content.ChildControls 
          where t as TabSection != null 
          select t as TabSection).ToList(); 
+0

這就是OfType ()可以。 – Lucas 2008-10-06 03:55:31

9

取決於你正在嘗試做的,其中之一可能做的伎倆:

List<Line> parentLineList1 = 
    (from t in content.ChildControls.OfType<TabSection>() 
    from p in t.ChildControls.OfType<Paragraph>() 
    from pl in p.ChildControls.OfType<Line>() 
    select pl).ToList(); 

List<Line> parentLineList2 = 
    (from TabSection t in content.ChildControls 
    from Paragraph p in t.ChildControls 
    from Line pl in p.ChildControls 
    select pl).ToList(); 

注意,一個使用OfType <牛逼> (),你正在使用。這將過濾結果並僅返回指定類型的項目。第二個查詢隱式使用Cast <T>(),它將結果轉換爲指定的類型。如果任何物品不能投射,則拋出異常。正如Turbulent Intellect所提到的,你應該儘可能不要調用ToList(),或者儘量避免它。

1

這裏是查詢方法的形式。

List<Line> parentLineList = 
    content.ChildControls.OfType<TabSections>() 
    .SelectMany(t => t.ChildControls.OfType<Paragraph>()) 
    .SelectMany(p => p.ChildControls.OfType<Line>()) 
    .ToList(); 
2
List<TabSection> tabList = (from t in content.ChildControls 
          let ts = t as TabSection 
          where ts != null 
          select ts).ToList(); 
+0

這就是OfType ()的用途。 – Lucas 2008-10-06 03:48:27