linq中的子对象

时间:2010-05-28 21:54:39

标签: linq-to-xml

我在发布之前检查过但无法找到解决方案。我是linq的新手,正在耗尽我的大脑来理解它。我有一个xml,并希望使用linq来填充具有子对象的对象。

xml和我的linq在下面。我的问题就在这一行

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

如何填写此子对象?

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 个答案:

答案 0 :(得分:3)

试试这个:

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()
            };