基于LayUi构造Tree无限层级树的数据结构

不使用递归 使用Foreach迭代进行运算
下面简单的写了一个控制台程序 虚拟了一些数据

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
public static List List = new List();
static void Main(string[] args)
{
var Result = YieldTree();
Console.WriteLine(JsonConvert.SerializeObject(Result));
Console.ReadLine();
}

    //迭代
    public static List<TreeModel> YieldTree()
    {
        //虚拟一串数据
        List.Add(new TreeModel() { Id = 1, Name = "测试1", Parentid = 0 });
        List.Add(new TreeModel() { Id = 2, Name = "测试2", Parentid = 1 });
        List.Add(new TreeModel() { Id = 3, Name = "测试3", Parentid = 2 });
        List.Add(new TreeModel() { Id = 4, Name = "测试4", Parentid = 3 });
        List.Add(new TreeModel() { Id = 5, Name = "测试5", Parentid = 3 });
        List.Add(new TreeModel() { Id = 6, Name = "测试6", Parentid = 0 });
        List.Add(new TreeModel() { Id = 7, Name = "测试7", Parentid = 6 });
        List.Add(new TreeModel() { Id = 8, Name = "测试8", Parentid = 6 });
        List.Add(new TreeModel() { Id = 9, Name = "测试9", Parentid = 8 });
        List.Add(new TreeModel() { Id = 10, Name = "测试10", Parentid = 9 });

        var dic = new Dictionary<dynamic, TreeModel>();
        foreach (var item in List)
        {
            dic.Add(item.Id, item);
        }
        foreach (var item in dic.Values)
        {
            if (dic.ContainsKey(item.Parentid))
            {
                if (dic[item.Parentid].Children == null) dic[item.Parentid].Children = new List<TreeModel>();
                dic[item.Parentid].Children.Add(item);
            }
        }
        return dic.Values.Where(x => x.Parentid == 0).ToList();
    }

    //数据模型
    public class TreeModel
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Parentid { get; set; }

        public List<TreeModel> Children { get; set; }
    }
}

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值