protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.Repeater1.DataSource = GetCategory();
this.Repeater1.DataBind();
}
}
#region 自定義
/// <summary>
/// 獲取分類
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
protected IList<ECSpider.Category.CategoryModel> GetCategory()
{
ECSpider.Category.Category db = new ECSpider.Category.Category();
IList<ECSpider.Category.CategoryModel> list = db.Find(null);
IList<ECSpider.Category.CategoryModel> result = new List<ECSpider.Category.CategoryModel>();
IList<ECSpider.Category.CategoryModel> temp = list.Where(t => t.ParentID == 0).ToList();
foreach (var item in temp)
{
result.Add(item);
GetSubCategory(list, result, item.ID, 1);
}
return result;
}
/// <summary>
/// 遞歸獲取下級分類
/// </summary>
/// <param name="list"></param>
/// <param name="result"></param>
/// <param name="categoryId"></param>
protected void GetSubCategory(IList<ECSpider.Category.CategoryModel> list, IList<ECSpider.Category.CategoryModel> result, int categoryId, int depth)
{
IList<ECSpider.Category.CategoryModel> temp = list.Where(t => t.ParentID == categoryId).ToList();
string nbsp = string.Empty;
for (int i = 0; i < depth; i++)
{
nbsp += " ";
}
for (int i = 0; i < temp.Count; i++)
{
temp[i].Name = nbsp + temp[i].Name;
result.Add(temp[i]);
depth++;
GetSubCategory(list, result, temp[i].ID, depth);
}
}
#endregion
{
if (!this.IsPostBack)
{
this.Repeater1.DataSource = GetCategory();
this.Repeater1.DataBind();
}
}
#region 自定義
/// <summary>
/// 獲取分類
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
protected IList<ECSpider.Category.CategoryModel> GetCategory()
{
ECSpider.Category.Category db = new ECSpider.Category.Category();
IList<ECSpider.Category.CategoryModel> list = db.Find(null);
IList<ECSpider.Category.CategoryModel> result = new List<ECSpider.Category.CategoryModel>();
IList<ECSpider.Category.CategoryModel> temp = list.Where(t => t.ParentID == 0).ToList();
foreach (var item in temp)
{
result.Add(item);
GetSubCategory(list, result, item.ID, 1);
}
return result;
}
/// <summary>
/// 遞歸獲取下級分類
/// </summary>
/// <param name="list"></param>
/// <param name="result"></param>
/// <param name="categoryId"></param>
protected void GetSubCategory(IList<ECSpider.Category.CategoryModel> list, IList<ECSpider.Category.CategoryModel> result, int categoryId, int depth)
{
IList<ECSpider.Category.CategoryModel> temp = list.Where(t => t.ParentID == categoryId).ToList();
string nbsp = string.Empty;
for (int i = 0; i < depth; i++)
{
nbsp += " ";
}
for (int i = 0; i < temp.Count; i++)
{
temp[i].Name = nbsp + temp[i].Name;
result.Add(temp[i]);
depth++;
GetSubCategory(list, result, temp[i].ID, depth);
}
}
#endregion
![.NET将从树形数据表里查询出来的普通集合重新构建成树形 - 郁郁 - 郁郁的博客 .NET将从树形数据表里查询出来的普通集合重新构建成树形 - 郁郁 - 郁郁的博客](http://img1.ph.126.net/WeDSyWTaPQQAGkGwiQ8POA==/6597795444331629880.png)