[ACCEPTED]-Doing a Cast Within a LINQ Query-.net-3.5

Accepted answer
Score: 27

Try this:

from TabSection t in content.ChildControls

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

Score: 11

Depending on what you are trying to do, one 10 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 9 uses OfType<T>(), which you were using. This 8 will filter the results and return only 7 the items of the specified type. The second 6 query implicitly uses Cast<T>(), which 5 casts the results into the specified type. If 4 any item cannot be cast, an exception is 3 thrown. As mentioned by Turbulent Intellect, you 2 should refrain from calling ToList() as 1 long as possible, or try to avoid it altogether.

Score: 3
List<TabSection> tabList = (from t in content.ChildControls
                            let ts = t as TabSection
                            where ts != null
                            select ts).ToList();


Score: 1

yes you can do the following:

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


Score: 1

And here's the query method form.

List<Line> parentLineList =
    .SelectMany(t => t.ChildControls.OfType<Paragraph>())
    .SelectMany(p => p.ChildControls.OfType<Line>())


More Related questions