Search code examples
c#linqlinqdatasource

Ordinal Position of Element in IENumerable Collection (Linq to XMl )


How do I embed the ordinal number of element as its attribute in this linq query.

var AllSections = from s in xmlDoc.Descendants("section")
                      select new
                      {
                          id = s.Attribute("id").Value,
                          themeTitle = s.Element("themeTitle").Value,
                          themeText = s.Element("themeText").Value,
                          objects = (from  a in AllObjects 
                                     join b in s.Descendants("object")
                                     on  a.Attribute("accessionNumber").Value equals
                                         b.Attribute("accessionNumber").Value
                                      //select a
                                      select new
                                       {
                                        //index = insert ordinal id/index of element

                                        ObjectTitle = a.Element("ObjectTitle").Value,
                                        ObjectText = a.Element("textentry").Value,


                                        }   
                                         )


                      };

Solution

  • @Jon Skeet gave you the appropriate overload of Select to use, and here is it in your query:

    var AllSections = from s in xmlDoc.Descendants("section")
        select new
        {
            id = s.Attribute("id").Value,
            themeTitle = s.Element("themeTitle").Value,
            themeText = s.Element("themeText").Value,
            objects = (from a in AllObjects 
                       join b in s.Descendants("object")
                           on a.Attribute("accessionNumber").Value
                           equals b.Attribute("accessionNumber").Value
                       select a).Select((a, index) =>
                           new
                           {
                               Index = index,
                               ObjectTitle = a.Element("ObjectTitle").Value,
                               ObjectText = a.Element("textentry").Value,
                           })
        };