假设我有平面格式的以下信息,例如对象列表:
List<Line> lines = new List<Line>
{
new Line{Id = 1, Level = 0},
new Line{Id = 2, Level = 1},
new Line{Id = 3, Level = 1},
new Line{Id = 4, Level = 2},
new Line{Id = 5, Level = 2},
new Line{Id = 6, Level = 1},
new Line{Id = 7, Level = 1},
new Line{Id = 8, Level = 2},
new Line{Id = 9, Level = 1}
};
每个对象都有一个id和一个级别。我希望最终得到一个嵌套列表。为此,我有一个课程,可以根据水平有一个孩子的列表。
public class NestedLine
{
public int Id;
public List<NestedLine> Children = new List<NestedLine>();
}
将该平面列表转换为嵌套列表的最简单方法是什么?
编辑:关于如何构建列表的唯一信息是行和级别的顺序。这应该是结果:
1
--2
--3
--4
--5
--6
--7
--8
--9
答案 0 :(得分:1)
这是我的尝试。
致电代码
List<Line> lines = new List<Line>
{
new Line{Id = 1, Level = 0},
new Line{Id = 2, Level = 1},
new Line{Id = 3, Level = 1},
new Line{Id = 4, Level = 2},
new Line{Id = 5, Level = 2},
new Line{Id = 6, Level = 1},
new Line{Id = 7, Level = 1},
new Line{Id = 8, Level = 2},
new Line{Id = 9, Level = 1}
};
NestedLine nestedLine = Recusrsive(lines, 0);
递归方法
private NestedLine Recusrsive(List<Line> lines, int listPos)
{
NestedLine retVal = new NestedLine();
Line line = lines[listPos];
retVal.Id = line.Id;
for (int iItem = listPos + 1; iItem < lines.Count; iItem++)
if (lines[iItem].Level == line.Level + 1)
retVal.Children.Add(Recusrsive(lines, iItem));
else if (lines[iItem].Level <= line.Level) return retVal;
return retVal;
}
答案 1 :(得分:0)
你能在这里提供更多信息吗?这让我觉得你真的在处理一个树形结构:
1
- &GT; 2
- &GT; 3
- &GT; - &GT; 4
- &GT; - &GT; 5
- &GT; 6
- &GT; 7
- &GT; - &GT; 8
- &GT; 9
首先想到的是为NestedLine类使用递归构造函数:
public NestedLine(List lines)
答案 2 :(得分:0)
使用堆栈跟踪每个级别添加的最后一个项目,随着时间推移和弹出:
var stack = new Stack<NestedLine>();
foreach (var line : lines) {
while (stack.Count > line.Level) {
// Pop items until the top element is one up from current level
stack.Pop()
}
var child = new NestedLine{Id = line.Id};
if (stack.Count > 0) {
// if there is a parent, add the child to its children
stack.Peek().Children.Add(child);
}
// add current line as the deepest item
stack.Push(child);
}
NestedLine root;
while (stack.Count) {
root = stack.Pop();
}
免责声明:我实际上并没有做太多C#编程,所以这可能包含一些微不足道的错误。