Search code examples
c#listcastingienumerablexelement

How to cast to a List<IEnumerable<XElement>>


I was doing this first to return a particular set of nodes under the parent node that had id equal to 1 which worked fantastically.

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

But i needed to do this multiple times and each to have there own instance so i thought to put them into a list but it doesn't even compile telling me error 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++;
        }

So I tried adding the cast List<IEnumerable<XElement>> just before LevelData.root. but then i get a invalidcastexception. I'm at a brick wall on where to go. Any advice?


Solution

  • The Where method doesn't return a List<>, it returns an IEnumerable<>, which is lazy-evaluated when it is enumerated.

    If you want an actual List<> object, stick a .ToList() at the end, and that will do it.