码迷,mamicode.com
首页 > Windows程序 > 详细

c#递归

时间:2017-08-13 13:24:21      阅读:207      评论:0      收藏:0      [点我收藏+]

标签: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#递归

标签:webapp   linq   gen   set   end   lin   items   name   children   

原文地址:http://www.cnblogs.com/WJ--NET/p/7290649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!