呃,我不確定這是否是你要找的東西,即使在其他答案之後。 但是,請看看:
自相關實體(節點)
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
(1)你能提供該列表中的類,所以我們不認爲只是一個TreeView? (2)你是指什麼*抓住一切*? – 2012-08-09 18:13:14
@AndreCalil:抓住一切:我是指所有父親和所有孩子的父親和他們的孩子的整個等級。不僅僅是我們可以點擊一個樹視圖的具體的一個......想象它就像導出一個樹視圖可以顯示的全部數據層次結構,如果它的所有節點一次被展開。 – Bohn 2012-08-09 18:16:22
第1條評論'//調用某個數據庫腳本'僅爲父節點和子數據獲取數據,並且不會比這更深? – Ankush 2012-08-09 18:17:31