c#遞迴

來源:互聯網
上載者:User

標籤:webapp   linq   gen   set   end   lin   items   name   children   

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#遞迴

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.