Bob*_*erg 29 .net c# linq .net-3.5
是否可以在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();
Run Code Online (Sandbox Code Playgroud)
代码继续进行一些查询,但要点是我必须从每个查询中创建一个List,以便编译器知道所有content.ChildControls类型TabSection的对象和所有类型的对象t.ChildControls都是类型Paragraph. ..等等等等.
在LINQ查询中是否有一种方法可以告诉编译器tin ?from t in content.ChildControls是TabSection?
Chr*_*man 27
试试这个:
from TabSection t in content.ChildControls
Run Code Online (Sandbox Code Playgroud)
此外,即使这不可用(或者您可能遇到的不同的未来场景),您也不会将所有内容转换为列表.转换为List会导致现场查询评估.但是如果删除ToList调用,则可以使用IEnumerable类型,这将继续推迟查询的执行,直到您实际迭代或存储在真实容器中.
Luc*_*cas 11
根据您要做的事情,其中一个可能会做到这一点:
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();
Run Code Online (Sandbox Code Playgroud)
请注意,您使用的是OfType <T>().这将过滤结果并仅返回指定类型的项目.第二个查询隐式使用Cast <T>(),它将结果转换为指定的类型.如果无法转换任何项目,则抛出异常.正如Turbulent Intellect所提到的,你应该尽可能地避免调用ToList(),或者尽量避免使用它.
| 归档时间: |
|
| 查看次数: |
50850 次 |
| 最近记录: |