Doing a Cast Within a LINQ Query

后端 未结 5 1531
借酒劲吻你
借酒劲吻你 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 parentLineList1 =
      (from t in content.ChildControls.OfType()
       from p in t.ChildControls.OfType()
       from pl in p.ChildControls.OfType()
       select pl).ToList();
    
    List 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(), which you were using. This will filter the results and return only the items of the specified type. The second query implicitly uses Cast(), 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.

提交回复
热议问题