1. 程式人生 > >c#遞歸

c#遞歸

page lis clas turn state ems bsp bag tom

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page
"; List<customer> list = new List<customer>() { new customer() { customerid="1",name="root",parentid="0"}, new customer() { customerid="2",name="child1",parentid="1"}, new customer() { customerid="3",name="
child2",parentid="1"} }; customer root = new customer(); root.customerid = "0"; root.name = "toosss"; root.parentid = "0"; string S= Get(); return View(); } public string Get() { var
Categorylist = new List<Category>() { new Category(){Id="00",pId="111", Name="總部",State=0}, new Category(){Id="01",pId="00",Name="賣場",State=1}, new Category(){Id="02",pId="01",Name="門店",State=1} }; var root = new Category() { Id = "00", pId = "111", Name = "根節點", State = 0 }; LoopToAppendChildren(Categorylist, root); string json = JsonConvert.SerializeObject(root); return json; } public void LoopToAppendChildren(List<Category> catelist, Category children) { var subItems = catelist.Where(x => x.pId == children.Id).ToList(); children.children = new List<Category>(); children.children.AddRange(subItems); foreach (var item in subItems) { LoopToAppendChildren(catelist, item); } } } public class Category { public string Id { get; set; } public string pId { get; set; } public string Name { get; set; } public int State { get; set; } public List<Category> children { get; set; } } public class customer { public string customerid { get; set; } public string name { get; set; } public string parentid { get; set; } public List<customer> children { get; set; } } }

c#遞歸