1. 程式人生 > >C#生成樹形結構泛型類

C#生成樹形結構泛型類

接口 message HERE mes ict test bsp ace spa

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 == 0) { 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); } }

C#生成樹形結構泛型類