【发布时间】:2011-08-15 21:44:27
【问题描述】:
已编辑:
我正在递归地将一些 XML 查询到对象中。每个对象都有一个子对象列表,如果有的话,应该引用它的父对象。
示例 XML:
<object attribute1="text" attribute2="text"/>
<object attribute1="text" attribute2="text">
<object attribute1="text" attribute2="text">
<object attribute1="text" attribute2="text">
</object>
示例 Linq:
private static List<MyObject> ParseMyObjects(XElement node, MyObject p)
{
List<MyObject> myobjs = (from x in node.Elements("object")
select new MyObject {
attribute1 = x.Attribute("attribute1 ").Value,
attribute2 = x.Attribute("attribute2 ").Value,
subObjects = ParseMyObjects(x, this), // the "this" key word can't refer to the MyObject being created in the query, but is there some other way of doing this?
parent= p
}).ToList();
return myobjs;
}
目前为了实现这一点,我正在递归遍历 MyObjects 列表,在它被查询并设置每个父级之后(排除上面的“父级”行)。
如果可能的话,我更喜欢在 Linq 查询中使用新实例化的对象的更优雅的解决方案。有什么想法吗?
编辑: 为了澄清(正如 BrokenGlass 在评论中所做的那样),代码评论所指的 this 是在查询中创建的 MyObject 的实例
【问题讨论】:
标签: linq