如何使用 linq 从分层数据结构投影新类型
我们有一个名为 Group 的类,它包含问题的集合并且它还包含组的集合(即我们有潜在的组嵌套)。
用 XML 表示,这可能看起来像这样:
<group id="Group1">
<questions>
<question id="questions11"/>
</questions>
<groups>
<group id="group12">
<questions>
<question id="question121"/>
</questions>
<groups>
<group id ="group121">
<questions>
<question id="question1211"/>
</questions>
</group>
<group id ="group122">
<questions>
<question id="question1221"/>
</questions>
</group>
</groups>
</group>
<group id="group13">
<questions>
<question id="question131"/>
</questions>
</group>
</groups>
</group>
我实际上简化了结构,为了简洁起见,我省略了每个组中我想要包含在投影中的属性。
我想做的是塑造一种新类型,其中包括此处的层次结构和一些属性,但排除其他一些属性和问题。
我完全坚持在 linq 中执行此操作。我查看了 SelectMany 但这不是我想要的。
TIA
We've got a Class called Group, it contains a collection of questions and it also contains collection of groups (i.e. we have a potential nesting of groups).
Expressed in XML this might look something like this:
<group id="Group1">
<questions>
<question id="questions11"/>
</questions>
<groups>
<group id="group12">
<questions>
<question id="question121"/>
</questions>
<groups>
<group id ="group121">
<questions>
<question id="question1211"/>
</questions>
</group>
<group id ="group122">
<questions>
<question id="question1221"/>
</questions>
</group>
</groups>
</group>
<group id="group13">
<questions>
<question id="question131"/>
</questions>
</group>
</groups>
</group>
I've actually simplified the structure, for brevity I've omitted bunch of properties in each group that I'll want to include in the projection.
What I want to do is shape a new type that includes the hierachical structure here and some of the properties but excludes some others and the questions.
I'm utterly stuck on hwo to do this in linq. I had a look at SelectMany but that wasn't what I wanted.
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要创建一个递归函数,将
元素转换为Group
实例,并为子
调用自身> 元素。You will need to make a recursive function that turns a
<group>
element into aGroup
instance and calls itself for the child<group>
elements.好吧...我不确定您将使用什么对象,但如果它来自来自xml,您可以尝试与此类似的操作:
对于您的 Questions 类...
您会称其为...
Well... I'm not sure what objects you would be working with, but if it was coming from xml, you might try something similar to this:
and for your Questions class...
You would call it like...