好吧,即使在其他答案之后,我也不确定这是否是您要寻找的东西。但是,请检查一下:
自相关实体(Node)
public class MyEntity
{
public MyEntity() { }
public MyEntity(string Name, int ID, int? ParentID)
{
this.Name = Name;
this.ID = ID;
this.ParentID = ParentID;
}
public string Name { get; set; }
public int ID { get; set; }
public int? ParentID { get; set; }
}
建树方法
public static StringBuilder GetFamilyTree(List<MyEntity> AllTheEntities)
{
StringBuilder Return = new StringBuilder();
List<MyEntity> OrderedEntities = AllTheEntities.OrderBy<MyEntity, int>(x => x.ID).ToList();
foreach (MyEntity CurrentEntity in AllTheEntities.Where<MyEntity>(x => !x.ParentID.HasValue))
{
Return.AppendLine(GetEntityTree(AllTheEntities, CurrentEntity));
}
return Return;
}
public static string GetEntityTree(List<MyEntity> AllTheEntities, MyEntity CurrentEntity, int CurrentLevel = 0)
{
StringBuilder Return = new StringBuilder();
Return.AppendFormat("{0}{1}", "\t".Repeat(CurrentLevel), CurrentEntity.Name);
Return.AppendLine();
List<MyEntity> Children = AllTheEntities.Where<MyEntity>(x => x.ParentID.HasValue && x.ParentID.Value == CurrentEntity.ID).ToList();
if (Children != null && Children.Count > 0)
{
foreach (MyEntity CurrentChildEntity in Children)
{
Return.Append(GetEntityTree(AllTheEntities, CurrentChildEntity, CurrentLevel + 1));
}
}
return Return.ToString();
}
一个小助手类
public static class StringExtension
{
public static string Repeat(this string text, int times)
{
string Return = string.Empty;
if (times > 0)
{
for (int i = 0; i < times; i++)
{
Return = string.Concat(Return, text);
}
}
return Return;
}
}
用法
List<MyEntity> AllMyEntities = new List<MyEntity>();
AllMyEntities.Add(new MyEntity("1", 1, null));
AllMyEntities.Add(new MyEntity("1.1", 2, 1));
AllMyEntities.Add(new MyEntity("1.1.1", 3, 2));
AllMyEntities.Add(new MyEntity("2", 4, null));
AllMyEntities.Add(new MyEntity("2.1", 5, 4));
Console.Write(GetFamilyTree(AllMyEntities).ToString());
结果
1
1.1
1.1.1
2
2.1