树结构类为:
/// <summary>
/// 树结构类
/// </summary>
public class TreeModel
{
public long Id { set; get; }
public long ParentId { set; get; }
public string Name { set; get; }
public List<TreeModel> TreeChildren { set; get; }
}
处理树结构:
public class TreeModelService
{
//<summary>
/// 公用递归(反射转换List)
/// <typeparam name="T"></typeparam>
/// <param name="allList">数据列表</param>
/// <param name="parentId">父级ID</param>
/// <param name="idField">id字段名称</param>
/// <param name="parentIdField">父级id字段名称</param>
/// <param name="nameField">name字段名称</param>
/// <returns></returns>
public List<TreeModel> ConversionList<T>(List<T> allList, long parentId, string idField, string parentIdField, string nameField)
{
List<TreeModel> list = new List<TreeModel>();
TreeModel model = null;
foreach (var item in allList)
{
model = new TreeModel();
foreach (System.Reflection.PropertyInfo p in item.GetType().GetProperties())
{
if (p.Name == idField)
{
model.Id = long.Parse(p.GetValue(item)?.ToString() ?? string.Empty);//判空
}
if (p.Name == parentIdField)
{
model.ParentId = long.Parse(p.GetValue(item)?.ToString() ?? string.Empty);//判空
}
if (p.Name == nameField)
{
model.Name = p.GetValue(item)?.ToString();//判空
}
}
list.Add(model);
}
return OperationParentData(list, parentId);
}
/// <summary>
/// 公用递归(处理递归最父级数据)
/// </summary>
/// <param name="treeDataList">树形列表数据</param>
/// <param name="parentId">父级Id</param>
/// <returns></returns>
public List<TreeModel> OperationParentData(List<TreeModel> treeDataList, long parentId)
{
var data = treeDataList.Where(x => x.ParentId == parentId);
List<TreeModel> list = new List<TreeModel>();
foreach (var item in data)
{
OperationChildData(treeDataList, item);
list.Add(item);
}
return list;
}
/// <summary>
/// 公用递归(递归子级数据)
/// </summary>
/// <param name="treeDataList">树形列表数据</param>
/// <param name="parentItem">父级model</param>
public void OperationChildData(List<TreeModel> treeDataList, TreeModel parentItem)
{
var subItems = treeDataList.Where(ee => ee.ParentId == parentItem.Id).ToList();
if (subItems.Count != 0)
{
parentItem.TreeChildren = new List<TreeModel>();
parentItem.TreeChildren.AddRange(subItems);
foreach (var subItem in subItems)
{
OperationChildData(treeDataList, subItem);
}
}
}
}
调用方法:id为要转化的类的主键,Parent_Id为要转化的类的父级键,Title为要显示的名称
/// <summary>
/// 查询目录树
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public List<TreeModel> GetTreeJson2()
{
var tree = new List<TreeModel>();
var list = _dao.QueryList<DictionaryType>().ToList();
if (list.Count > 0)
{
tree = new TreeModelService().ConversionList(list, 0, "Id", "Parent_Id", "Title");
}
return tree;
}
简单记录一下!!