不使用递归 使用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; }
}
}
}