是否可以在 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 查询中是否有一种方法可以告诉编译器 from t in content.ChildControls
中的 t
是 TabSection
?
最佳答案
试试这个:
from TabSection t in content.ChildControls
此外,即使这不可用(或者对于您可能遇到的不同的 future 场景),您也不会局限于将所有内容转换为列表。转换为 List 会导致当场进行查询评估。但是,如果删除 ToList 调用,则可以使用 IEnumerable 类型,它将继续推迟查询的执行,直到您实际迭代或存储在真实容器中。
关于c# - 在 LINQ 查询中进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/158634/