c# - 如何转换为 List<IEnumerable<XElement>>

标签 c# list casting ienumerable xelement

我首先这样做是为了在父节点下返回一组特定的节点,这些节点的 id 等于 1,效果非常好。

IEnumerable<XElement> world1 = LevelData.root.
                               Elements("world").
                               Where(element => (int?)element.Attribute("id") == 1);

但我需要多次执行此操作,并且每次都有自己的实例,所以我想将它们放入列表中,但它甚至没有编译并告诉我错误 CS0266:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List>'. An explicit conversion exists (are you missing a cast?)

List<IEnumerable<XElement>>[] World = new List<IEnumerable<XElement>>[noofworlds];

        foreach (List<IEnumerable<XElement>> wn in World)
        {
            Debug.WriteLine("World: "+w);

            //this will make a list of all the nodes (elements) within the world specified by the id tag
            World[w] =  LevelData.Root.Elements("world").Where(element => (int?)element.Attribute("id") == 1);//with id == to i
            w++;
        }

所以我尝试添加 Actor List<IEnumerable<XElement>>就在LevelData.root.之前 但后来我得到一个无效的castexception。我在去哪里的砖墙上。有什么建议吗?

最佳答案

Where方法不返回 List<> , 它返回一个 IEnumerable<> ,它在枚举时被惰性求值。

如果你想要一个实际的 List<>对象,贴一个.ToList()最后,这样就可以了。

关于c# - 如何转换为 List<IEnumerable<XElement>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14821258/

相关文章:

跨嵌套列表的 rbind 数据帧

c++ - 我怎样才能摆脱这个 reinterpret_cast,或者这种用法可以吗?

c - 针对用户定义的函数类型转换错误生成编译器警告

c# - 如何使用标记注册将 .ascx 文件导入 .aspx 页面?

c# - 在启动 WCF 服务时调用方法

c# - 我应该怎么做才能使一个小型开源项目保持活跃和可持续发展?

list - Java 8 流与迭代器性能

c# - LINQ to XML 中的 XmlDocumentFragment 等效吗?

python - 将列表列表构建为 csv/Excel 的列和行

转换为 int 和浮点错误?