标签:stat rgb rgba sele tree contains 接口 list menu
数据结构接口:
/// <summary> /// 实体类必须实现接口 /// </summary> public interface IToTreeModel { int Id { get; set; } int ParentId { get; set; } List<IToTreeModel> Children { get; set; } void AddChilrden(IToTreeModel node); }
实现模型:
/// <summary> /// 实体类实例 /// </summary> public class ViewModel : IToTreeModel { public int Id { get; set; } public int ParentId { get; set; } public string Label { set; get; } public List<IToTreeModel> Children { get; set; } public void AddChilrden(IToTreeModel node) { if (Children == null) Children = new List<IToTreeModel>(); this.Children.Add(node); } }
方法处理:
/// <summary> /// 处理 /// </summary> /// <typeparam name="T"></typeparam> public class ToTree<T> where T : IToTreeModel { public static List<T> ToDo(List<T> models,int ParentId=0,bool IsParentId=true) { var dtoMap = new Dictionary<int, T>(); foreach (var item in models) { if (!dtoMap.ContainsKey(item.Id)) { dtoMap.Add(item.Id, item); } } List<T> result = new List<T>(); foreach (var item in dtoMap.Values) { if (IsParentId) { if (item.ParentId == ParentId) { result.Add(item); } else { if (dtoMap.ContainsKey(item.ParentId)) { dtoMap[item.ParentId].AddChilrden(item); } } } else { if (item.Id == ParentId) { result.Add(item); } else { if (dtoMap.ContainsKey(item.ParentId)) { dtoMap[item.ParentId].AddChilrden(item); } } } } return result; } }
使用:
ar list = db.Mode.Select(x => new MenuTree { Id = x.ID, Label = x.Name, ParentId = x.ParentId }).ToList(); var data = ToTree<MenuTree>.ToDo(list);
data数据就是最后的数据
标签:stat rgb rgba sele tree contains 接口 list menu
原文地址:https://www.cnblogs.com/ruiyuan/p/13933278.html