深度第一平整使用LINQ的对象层次集合 [英] Depth-first flattened collection of an object hierarchy using LINQ

查看:180
本文介绍了深度第一平整使用LINQ的对象层次集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的层次结构(MasterNode - >子节点),其中主站和子节点都是同一类型的,而且只有两个级别(最高级别和孩子)这样的('A'是D,E的父母和楼'b'是G的父母等)

I have an object hierarchy (MasterNode -> ChildNodes) where master and child nodes are of the same type, and there are only two levels (top level and children) like this ('A' is parent of D,E and F, 'B' is parent of G, etc)

A--+
|  D
|  E
|  F
|
B--+
|  G
|
C--+
   H
   I



假设我有一个 MasterNodes 作为父对象的IEnumerable(A,B,C),并给出父对象的 X 我可以通过的 X即可获得其子女的IEnumerable。孩子

Suppose I have a MasterNodes as an IEnumerable of the parent objects (A,B,C) and given a parent object X I can get an IEnumerable of its children by X.children

我知道我可以枚举所有的叶(子节点)的的SelectMany 方式或通过使用

I know that I can enumerate all of the leaf (child nodes) with the SelectMany method or by using

from parent in Masternodes
from child in parent.children
select child

这会给我这个序列:

[D,E,F,G,H,I]

,但这不是什么我要求。

,but this is not what I am asking for.

什么是LINQ查询来获得在MasterNodes收集的对象的深度优先顺序?(返回第一父母那么所有的孩子,那么下一个父它所有的孩子等等等等)

What is the LINQ query to get a depth-first sequence of the objects in the MasterNodes collection? (return first parent then all of its children then next parent then all of its children etc etc)

预期的结果应该是这样一个顺序:

The expected result should be a sequence like this:

[A,D,E,F,B,G,C,H,I]

更新

我要求纯.NET准备LINQ。我知道我可以定义自己的方法做事,但我想这仅仅是基于该框架提供的方法什么的。

I am asking for pure .NET ready LINQ. I know that I can define my own methods to do things, but I want something that is based only on the framework provided methods.

推荐答案

因为你只有两个级别,下面的方法应该工作:

Since you have only two levels, the following approach should work:

var result = (from parent in masternodes
              select new Node[] { parent }.Concat(parent.children)).SelectMany(i => i);



首先,它创建父可枚举加上其子:

First, it creates enumerables of the parent plus its children:

[A, D, E, F]
[B, G]
[C, H]

,然后将其压平他们与的SelectMany

and then it flattens them with SelectMany.

这篇关于深度第一平整使用LINQ的对象层次集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆