user9993
user9993

Reputation: 6170

LINQ to Objects - Assign list to property

I am trying to write a LINQ to Objects/XML query that will create objects. I have a class which has a property IList of SomeModelClass. SomeModelClass also has several IList's which need to be populated from the XML.

This is the first time I've attempted to query multiple levels of nested XML and I am unsure how to proceed.

Currently the code does not compile because select new does not seem to be able to be nested. How can I actually query the nested XML to create an object that has a list of objects which also has a list of strings?

I have shown the code that I have attempted to far.

I have a class like this:

public class MyClass
{
    public string Name { get; set }
    public IList<SomeModelClass> ModelList { get; set; }
}

And this is my model class:

public class SomeModelClass
{
    public IList<string> MyList1 { get; set; }
}

The XML looks like this:

  <someXml>
    <section name="test">
      <myModelClassXml>
        <someValue value="string1" />
        <someValue value="string2" />
        <someValue value="string3" />
      </myModelClassXml>
    </section>

    <section name="test2">
      <myModelClassXml>
        <someValue value="string1" />
      </myModelClassXml>
    </section>
  </someXml>

And the code I have so far:

    var query = (from r in xdoc.Descendants("someXml").Descendants("section")
                 select new MyClass()
                 {
                     Name = r.Attribute("name").Value,

                     //Make list of SomeModelClass AND ALSO populate SomeModelClass's lists
                     select new SomeModelClass
                     {
                        MyList1 = What needs to be here?
                     }

                 });

Upvotes: 0

Views: 1865

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

This should give you the correct result:-

List<MyClass> result = xdoc.Root.Descendants("section")
            .Select(x => new MyClass
               {
                   Name = (string)x.Attribute("name"),
                   ModelList = x.Elements("myModelClassXml")
                                .Select(y => new SomeModelClass 
                    {
                        MyList1 = y.Elements("someValue")
                                   .Select(z => (string)z.Attribute("value")).ToList()
                                                               }).ToList()
                    }).ToList();

First find all the descendants of section then project it to MyClass. Now since myModelClassXml is direct child to section, we can use Elements to further fetch someValue element and its value attribute.

Upvotes: 1

Related Questions