using System.Collections.Generic; using System.Linq; namespace CommonTool { public class BootStrapTree { public static BootStrapTree Inatance = new BootStrapTree(); public Tree CreatTree(List pcTrees) { Tree loRoot = null; var lcTrees = pcTrees.Where(a => a.FatherId == "0").ToList(); if (lcTrees.Count() == 1) { loRoot = lcTrees.FirstOrDefault(); if (loRoot != null) { loRoot.ChildNodes = pcTrees.Where(a => a.FatherId == loRoot.Id && a.FatherId != "0").ToList(); if (loRoot.ChildNodes.Any()) { foreach (Tree tree in loRoot.ChildNodes) { CreatTree(pcTrees, tree.Id); } } } } return loRoot; } public Tree CreatTree(List pcTrees,string id) { Tree loRoot = null; var lcTrees = pcTrees.Where(a => a.Id == id && a.FatherId != "0").ToList(); if (lcTrees.Count() == 1) { loRoot = lcTrees.FirstOrDefault(); if (loRoot != null) { loRoot.ChildNodes = pcTrees.Where(a => a.FatherId == loRoot.Id && a.FatherId != "0").ToList(); if (loRoot.ChildNodes.Any()) { foreach (Tree tree in loRoot.ChildNodes) { CreatTree(pcTrees,tree.Id); } } } } return loRoot; } } public class Tree { //public Tree(IQueryable trees) //{ // Trees = trees; //} //public Tree newTree = BootStrapTree.Inatance.CreatTree(Trees); //public static IQueryable Trees { get; set; } public string Id { get; set; } public string Text { get; set; } public string FatherId { get; set; } //public int Depth { get; set; } //public string IsLeaf { get; set; } //public int Sort { get; set; } public List ChildNodes { get; set; } public string ToJason() { string lcRetVal = "{ \r\n"; lcRetVal += "\"id\": \"" + Id + "\",\r\n"; lcRetVal += "\"text\": \"" + Text+ "\""; if (ChildNodes != null) { lcRetVal += ",\r\n\"nodes\": ["; string lcString = ""; foreach (Tree loChild in ChildNodes) { lcString += (lcString == "" ? "" : ",") + loChild.ToJason(); } lcRetVal += lcString; lcRetVal += "] \r\n"; } lcRetVal += "} \r\n"; return lcRetVal; } public string ToJbson() { return "[ "+ ToJason()+"]"; } } }