我有一个如下结构的列表;
public class ListDTO
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
}
在列表数据中存储以下格式
我想通过以下格式过滤空格。不需要分层列表;只需要带空格的简单列表
答案 0 :(得分:0)
这是一种快速的方法。也许不是最好的,但我确信有人可以在递归时提出更好的建议。
var list = new List<ListDTO>()
{
new ListDTO() { ID = 1, ParentID = 0, Name = "Name 1" },
new ListDTO() { ID = 2, ParentID = 0, Name = "Name 2" },
new ListDTO() { ID = 3, ParentID = 2, Name = "Name 11111" },
new ListDTO() { ID = 4, ParentID = 3, Name = "Name 33333" }
};
Func<ListDTO, string, string> returnIdentatiton = null;
returnIdentatiton = (dto, identation) =>
{
if (dto.ParentID == 0)
return identation + string.Empty;
else
return returnIdentatiton(list.First(d => d.ID == dto.ParentID), identation + " ");
};
list.ForEach(l =>
{
Console.WriteLine(returnIdentatiton(l, string.Empty) + l.Name);
});