tags:

views:

41

answers:

2

I checked before I posted but couldn't find a solution. I'm new to linq and it is draining my brain to understand it. I have an xml and want to use linq to fill object that has a child object.

the xml and my linq is below. My issue is on this line

TaskItems = t.Elements("taskdetail").ToList<TaskItem>() //this line doesn't work

how do I fill this child object?

var task1 = from t in xd.Descendants("taskheader")
            select new
            {
                Id = t.Element("id").Value,
                Name = t.Element("name").Value,
                IsActive = Convert.ToBoolean(Convert.ToInt16(t.Element("isactive").Value))
                TaskItems = t.Elements("taskdetail").ToList<TaskItem>()
            };

<tasks>
  <taskheader>
    <id>1</id>
    <name>some task</name>
    <isactive>1</isactive>
    <taskdetail>
      <taskid>1</taskid>
      <name>action1</name>
      <value>some action</value>
    </taskdetail>
    <taskdetail>
      <taskid>1</taskid>
      <name>action2</name>
      <value>some other action</value>
    </taskdetail>
  </taskheader>
</tasks>

public class Task
{
        public int Id;
        public string Name;
        public bool IsActive;

        public List<TaskItem> TaskItems = new List<TaskItem>();
}

public class TaskItem
{
        public int TaskId;
        public string Name;
        public string Value;
}
+1  A: 

Try this:

var tasks = from t in xd.Descendants("taskheader")
            select new Task
            {
                Id = (int)t.Element("id"),
                Name = t.Element("name").Value,
                IsActive = t.Element("isactive").Value == "1",
                TaskItems = t.Elements("taskdetail").Select(e => new TaskItem
                {
                    TaskId = (int)e.Element("taskid"),
                    Name = (string)e.Element("name"),
                    Value = (string)e.Element("value"),
                }).ToList()
            };
Mark Byers
This looks like it would return a list of anonymous type. Did you forget to specify `select new Task` or will this work as is?
Dennis Palmer
@Dennis Palmer: It probably should be new Task, I'll update the answer. The original code has the same bug/feature - I changed only the `TaskItems = ...` part.
Mark Byers
@Dennis Palmer: OK, I've updated it. I also had to also cast the Id to an integer to get it to compile, and while I was at it I simplified the logic for calculating `IsActive`. Thanks for the comment.
Mark Byers
@Mark Byers: Cool, that looks more like what the OP really intended to get.
Dennis Palmer
Thats awesome, thanks Mark, it works perfectly
gangt
A: 

Thanks for all this, this is exactly what I need. But I still Have a Problem : when i make a deserialization, and i have an empty list(empty xElement) the list is null and I receive an exception, do you have a solution please

mcloof