如何转换为List <IEnumerable <XElement >>

Rus*_*ill 2 c# ienumerable xelement casting list

我首先要在父节点下返回一组特定的节点,这些节点的id等于1,这非常有效.

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

但我需要多次这样做,每个都有自己的实例,所以我想把它们放入一个列表,但它甚至没有编译告诉我错误CS0266:

无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'System.Collections.Generic.List>'.存在显式转换(您是否错过了演员?)

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++;
        }
Run Code Online (Sandbox Code Playgroud)

所以我尝试在List<IEnumerable<XElement>>之前添加演员,LevelData.root. 但后来我得到了一个invalidcastexception.我在哪里可以去砖墙.有什么建议?

Dav*_*Yaw 5

Where方法不返回a List<>,它返回a IEnumerable<>,在枚举时进行惰性求值.

如果你想要一个真实的List<>物体,最后坚持.ToList()一下,就可以了.