NET 通用方法:把扁平数据转换为树形数据结构【集合】
1.扁平数据为:
Code ParentCode Name Remark 2111011043240001 0 Lv0 2111011043260002 2111011043240001 Lv0-1 2111011043260004 2111011043260002 Lv0-1-1 附属信息1:Lv0-1-1 2111011043260010 2111011043260002 Lv0-1-2 附属信息1:Lv0-1-2 2111011043260016 2111011043260002 Lv0-1-3 附属信息1:Lv0-1-3 2111011043260022 2111011043260002 Lv0-1-4 附属信息1:Lv0-1-4 2111011043260028 2111011043260002 Lv0-1-5 附属信息1:Lv0-1-5 2111011043260032 2111011043240001 Lv0-2 2111011043270034 2111011043260032 Lv0-2-1 附属信息1:Lv0-2-1 2111011043270040 2111011043260032 Lv0-2-2 附属信息1:Lv0-2-2 2111011043270046 2111011043260032 Lv0-2-3 附属信息1:Lv0-2-3 2111011043270050 2111011043240001 Lv0-3 附属信息1:Lv0-3 2111011043270054 2111011043240001 Lv0-5 附属信息1:Lv0-5 2111011043270056 0 Lv1 2111011043270057 2111011043270056 Lv1-1 2111011043270059 2111011043270057 Lv1-1-1 附属信息1:Lv1-1-1 2111011043270063 2111011043270056 Lv1-2 附属信息1:Lv1-2 2111011043270067 2111011043270056 Lv1-3 附属信息1:Lv1-3
2.通用方法
/// <summary> /// 通用方法 /// </summary> /// <param name="dbList">源数据集合</param> /// <param name="parentCode">父级值</param> /// <param name="orderFunc">排序函数</param> /// <returns></returns> public static List<TreeModel> GetChildrenList(List<DbModel> dbList, string parentCode, Func<IEnumerable<TreeModel>, IEnumerable<TreeModel>> orderFunc = null) { var treeList = new List<TreeModel>(); if (dbList.IsNullOrEmpty()) return treeList; // 因为框架原因,DbModel不能进行泛型约束,只有TreeModel能直接取到树形相关字段 var convertTreeList = dbList.MapTo<DbModel, TreeModel>(); // 筛选数据 var whereDbList = convertTreeList.Where(x => parentCode.Equals(x.ParentCode)); // 对数据进行排序 if (!whereDbList.IsNullOrEmpty() && orderFunc != null) whereDbList = orderFunc(whereDbList); if (whereDbList.IsNullOrEmpty()) return treeList; foreach (var item in whereDbList) { var children = GetChildrenList(dbList, item.Code); item.Children = children; treeList.Add(item); } return treeList; } }
3.调用
var treeList = CommonTreeBll<DbModel, TreeModel>.GetChildrenList(dbList, "0", p => p.OrderBy(x => x.Name).ThenBy(x => x.Remark));
4.接口
public interface ITreeBase<TreeModel> { /// <summary> /// 当前节点主键 /// </summary> string Code { get; set; } /// <summary> /// 上级节点主键,默认为0[根节点] /// </summary> string ParentCode { get; set; } /// <summary> /// 子节点集合 /// </summary> List<TreeModel> Children { get; set; } }
5.DbModel & TreeModel
public partial class DbModel { // ... } public class TreeModel : DbModel, ITreeBase<TreeModel > { public List<TreeModel > Children { get; set; } }