C#生成树形结构泛型类

时间:2022-11-19 22:26:44

C#生成树形结构泛型类,使用方法: ToTree<ShowMessageUpdatesTableTreeViewModel>.ToDo(models)

public class ToTree<T> where T : IToTreeModel
{
public static List<T> ToDo(List<T> models)
{
var dtoMap = new Dictionary<int, T>();
foreach (var item in models)
{
dtoMap.Add(item.Id, item);
}
List<T> result = new List<T>();
foreach (var item in dtoMap.Values)
{
if (item.ParentId == )
{
result.Add(item);
}
else
{
if (dtoMap.ContainsKey(item.ParentId))
{
dtoMap[item.ParentId].AddChilrden(item);
}
}
}
return result;
}
}

实体类必须实现接口:

public interface IToTreeModel
{
int Id { get; set; }
int ParentId { get; set; }
List<IToTreeModel> children { get; set; }
void AddChilrden(IToTreeModel node);
}

实体类实例:

    public class ShowMessageUpdatesViewModel: IToTreeModel
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public List<IToTreeModel> children { get; set; }
public void AddChilrden(IToTreeModel node)
{
if (children == null)
children = new List<IToTreeModel>();
this.children.Add(node);
}
}