Doing a Cast Within a LINQ Query

后端 未结 5 1530
借酒劲吻你
借酒劲吻你 2021-02-01 03:51

Is it possible to do a cast within a LINQ query (for the compiler\'s sake)?

The following code isn\'t terrible, but it would be nice to make it into one query:



        
相关标签:
5条回答
  • 2021-02-01 04:00

    Depending on what you are trying to do, one of these might do the trick:

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

    Note that one uses OfType<T>(), which you were using. This will filter the results and return only the items of the specified type. The second query implicitly uses Cast<T>(), which casts the results into the specified type. If any item cannot be cast, an exception is thrown. As mentioned by Turbulent Intellect, you should refrain from calling ToList() as long as possible, or try to avoid it altogether.

    0 讨论(0)
  • 2021-02-01 04:07
    List<TabSection> tabList = (from t in content.ChildControls
                                let ts = t as TabSection
                                where ts != null
                                select ts).ToList();
    
    0 讨论(0)
  • 2021-02-01 04:10

    yes you can do the following:

    List<TabSection> tabList = (from t in content.ChildControls
                                where t as TabSection != null
                                select t as TabSection).ToList();
    
    0 讨论(0)
  • 2021-02-01 04:16

    Try this:

    from TabSection t in content.ChildControls
    

    Also, even if this were not available (or for a different, future scenario you may encounter), you wouldn't be restricted to converting everything to Lists. Converting to a List causes query evaluation on the spot. But if you removing the ToList call, you could work with the IEnumerable type, which would continue to defer the execution of the query until you actually iterate or store in a real container.

    0 讨论(0)
  • 2021-02-01 04:21

    And here's the query method form.

    List<Line> parentLineList =
      content.ChildControls.OfType<TabSections>()
        .SelectMany(t => t.ChildControls.OfType<Paragraph>())
        .SelectMany(p => p.ChildControls.OfType<Line>())
        .ToList();
    
    0 讨论(0)
提交回复
热议问题