[英]Sorting elements by number parent-child relationship while looping through a list in c#
I have such a list;我有这样的清单;
List<int> numbers = new List<int>
{
2,
4,
4,
2,
4,
4,
6,
6,
8,
2,
4
};
and i want to list it as below我想把它列出如下
2
4
4
2
4
4
6
6
8
2
4
Please note that these are a dynamic list.请注意,这些是动态列表。 and the 2's are the main elements the 4's are the 2's child elements etc..并且 2 是主要元素 4 是 2 的子元素等。
I've used this example for a simpler explanation, what I really want to do is list HTML elements by parent-child relationship with tag indexes.我用这个例子来做一个更简单的解释,我真正想做的是通过标签索引的父子关系列出 HTML 元素。
What is the ideal way to list as in this solution?在此解决方案中列出的理想方式是什么?
Add indentation based on your values根据您的值添加缩进
var list = numbers
.Select(i => new string('\t', i / 2 - 1) + i)
.ToList();
Here is two ways.这里有两种方法。
Using <pre>
and '\t':使用<pre>
和 '\t':
@foreach (var number in numbers)
{
<div class="d-flex flex-row"><pre>@(new string('\t',number))</pre>@number</div>
}
or或者
Using a render fragment of choice:使用选择的渲染片段:
@foreach (var number in numbers)
{
<div class="d-flex flex-row">
@for (var i = 0; i < number; i++)
@SomeGap
@number
</div>
}
@code {
List<int> numbers = new List<int>
{
...
};
RenderFragment SomeGap => @<div>gap</div>;
}
You could extend the second method further by making the render fragment a parameter or static.您可以通过将渲染片段设置为参数或静态来进一步扩展第二种方法。 In a hierarchical arrangement you could pass the depth as a parameter;在分层排列中,您可以将深度作为参数传递;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.