C# 在表格视图中显示多层/多级项目
我在树状视图中有一个多层或多层项目列表,如下所示。 但我必须在表格视图中显示这些多层或多层项目,其级别如下所示 根据我的要求,我使用了以下代码:C# 在表格视图中显示多层/多级项目,c#,asp.net-core,C#,Asp.net Core,我在树状视图中有一个多层或多层项目列表,如下所示。 但我必须在表格视图中显示这些多层或多层项目,其级别如下所示 根据我的要求,我使用了以下代码: public class Comment { public int Id { get; set; } public int ParentId { get; set; } public string Text { get; set; } public List<Comment> Childr
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);
}
}
}
公共类注释
{
公共int Id{get;set;}
public int ParentId{get;set;}
公共字符串文本{get;set;}
公共列表子项{get;set;}
}
班级计划
{
静态void Main()
{
列表类别=新列表()
{
新注释(){Id=1,Text=“Category B”,ParentId=0},
新注释(){Id=2,Text=“Child B”,ParentId=1},
新注释(){Id=3,Text=“类别A”,ParentId=0},
新注释(){Id=4,Text=“Child A”,ParentId=3},
新注释(){Id=5,Text=“Grand Child”,ParentId=4}
};
列表层次结构=新列表();
层次结构=类别
。其中(c=>c.ParentId==0)
.Select(c=>newcomment(){
Id=c.Id,
Text=c.Text,
ParentId=c.ParentId,
Children=GetChildren(categories,c.Id)})
.ToList();
等级交叉道(等级);
Console.ReadLine();
}
公共静态列表GetChildren(列表注释,int-parentId)
{
回复评论
.Where(c=>c.ParentId==ParentId)
.Select(c=>newcomment{
Id=c.Id,
Text=c.Text,
ParentId=c.ParentId,
Children=GetChildren(注释,c.Id)})
.ToList();
}
公共静态void层次结构(列表层次结构)
{
if(层次结构!=null)
{
foreach(层次结构中的变量项)
{
WriteLine(string.Format(“{0}{1}”,item.Id,item.Text));
层次交叉道(项目.儿童);
}
}
}
它给了我所需格式的数据。
我如何在表格视图中以其级别呈现数据,如上面第二张图片所示(项目级别不固定)