代码之家  ›  专栏  ›  技术社区  ›  Bob Wintemberg

在LINQ查询中执行强制转换

  •  29
  • Bob Wintemberg  · 技术社区  · 18 年前

    是否可以在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查询中是否有方法告诉编译器 t 在里面 from t in content.ChildControls ?

    5 回复  |  直到 9 年前
        1
  •  27
  •   Chris Ammerman    18 年前

    试试这个:

    from TabSection t in content.ChildControls
    

        2
  •  11
  •   Lucas    18 年前

    根据您尝试执行的操作,以下操作之一可能会奏效:

    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();
    

        3
  •  2
  •   Michael Damatov    18 年前
    List<TabSection> tabList = (from t in content.ChildControls
                                let ts = t as TabSection
                                where ts != null
                                select ts).ToList();
    
        4
  •  1
  •   Jared xxtesaxx    18 年前

    是的,您可以执行以下操作:

    List<TabSection> tabList = (from t in content.ChildControls
                                where t as TabSection != null
                                select t as TabSection).ToList();
    
        5
  •  1
  •   Amy B    18 年前

    这是查询方法表单。

    List<Line> parentLineList =
      content.ChildControls.OfType<TabSections>()
        .SelectMany(t => t.ChildControls.OfType<Paragraph>())
        .SelectMany(p => p.ChildControls.OfType<Line>())
        .ToList();
    
    推荐文章