在表格视图中显示多层/多层次项目

时间:2017-06-06 05:57:55

标签: c# asp.net-core

我在树视图中有一个多层或多层项目列表,如下所示。 enter image description here

但我必须在表格视图中显示这些多层或多层项目,其级别如下enter image description here

根据我的要求,我使用了代码:

 public class Comment
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Text { get; set; }        
    public List<Comment> Children { get; set; }
}

class Program
{
    static void Main()
    {
    List<Comment> categories = new List<Comment>()
        {
            new Comment () { Id = 1, Text = "Category B", ParentId = 0},
            new Comment() { Id = 2, Text = "Child B", ParentId = 1 },
            new Comment() { Id = 3, Text = "Category A", ParentId = 0 },
            new Comment() { Id = 4, Text = "Child A", ParentId = 3 },
            new Comment() { Id = 5, Text = "Grand Child", ParentId = 4 }
        };

        List<Comment> hierarchy = new List<Comment>();
        hierarchy = categories
                        .Where(c => c.ParentId == 0)
                        .Select(c => new Comment() { 
                              Id = c.Id, 
                              Text = c.Text, 
                              ParentId = c.ParentId, 
                              Children = GetChildren(categories, c.Id) })
                        .ToList();

        HieararchyWalk(hierarchy);

        Console.ReadLine();
    }

    public static List<Comment> GetChildren(List<Comment> comments, int parentId)
    {
        return comments
                .Where(c => c.ParentId == parentId)
                .Select(c => new Comment { 
                    Id = c.Id, 
                    Text = c.Text, 
                    ParentId = c.ParentId, 
                    Children = GetChildren(comments, c.Id) })
                .ToList();
    }

    public static void HieararchyWalk(List<Comment> hierarchy)
    {
        if (hierarchy != null)
        {
            foreach (var item in hierarchy)
            {
                Console.WriteLine(string.Format("{0} {1}", item.Id, item.Text));
                HieararchyWalk(item.Children);
            }
        }
    }

它以所需格式提供数据。 如何在表格视图中使用它的级别呈现数据,如上面的第二张图片所示(项目的层次不固定)

0 个答案:

没有答案