Search code examples
c#linqxelement

LINQ query nested loop with multiple select statements


I'm trying to generate XML, to create the nested XElements I am using LINQ.

However, I'm struggling to then create more nested elements based on the previous LINQ loop.

This is what I am trying:

List<MessageValues> desValues;

XElement xml = new XElement(ns + "Message_Name",
          new XAttribute(XNamespace.Xmlns + "i", nsi.NamespaceName),
              from sr in subNames
              select new XElement(sr),
              from v in desValues
              where v.SubRoot = sr //need a way of doing this
              select new XElement(v.Key, v.Value));

Basically I need to know whether there's a way of nesting 2 LINQ loops but still selecting after each iteration.

Hope this makes enough sense..


Solution

  • Try this:

    XElement xml =
        new XElement(
            ns + "Message_Name",
            new XAttribute(
                XNamespace.Xmlns + "i",
                nsi.NamespaceName),
            from sr in subNames
            select new XElement(sr),
            from sr in subNames
            from v in desValues
            where v.SubRoot = sr
            select new XElement(v.Key, v.Value));