tags:

views:

38

answers:

1

Hi - looking for best practice in converting a parent-child relationship using Linq to XML

In this case i have a Domain class which contains a Group[]

What I want to do is iterate over the Groups[] in d (domains) and create the XElements in one hit.

        XElement _customers = new XElement("Domains",
                                from c in d
                                orderby c.id //descending  
                                select new XElement("Domain",
                      // something like-->  new XElement("Groups", c.id),
                      // loop through d.Group and add new XElement...
                                    new XElement("id", c.id),
                                    new XAttribute("name", c.name),
                                    new XElement("ismanaged", c.IsManaged.ToString()
                                    )));

Thanks in advance

+1  A: 

You can use nested queries to do this.

Assuming your classes look like this (simplifying a little bit):

public class Domain
{
    public string Name;
    public List<Group> Groups;
}

public class Group
{
    public string GroupId;
}

You can create LINQ to XML representation in one go like this:

XElement domains = new XElement("Domains",
    from domain in domains
    select new XElement("Domain",
        new XAttribute("name", domain.Name),
        from group in domain.Groups
        select new XElement("Group",
            new XAttribute("id", group.GroupId))
    ));

The "trick" is that if you pass an IEnumerable as one of the parameters to the XElement constructor, the constructor will enumerate over it and add each item separately.

Vitek Karas MSFT
Thanks Vitek that seems to do the trick.
MikeW