Rendering a hierarchy using LINQ?

前端 未结 6 1021
终归单人心
终归单人心 2020-12-10 08:05

Let say we have a class

Category
{
   ID,
   Name,
   ParentID
}

and a List

1, \'Item 1\', 0
2, \'Item 2\', 0
3, \'Item 3\'         


        
6条回答
  •  無奈伤痛
    2020-12-10 08:48

    You can use recursion:

    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int ParentID { get; set; }
        public List Children { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            List categories = new List()
            {
                new Category () { ID = 1, Name = "Item 1", ParentID = 0},
                new Category() { ID = 2, Name = "Item 2", ParentID = 0 },
                new Category() { ID = 3, Name = "Item 3", ParentID = 0 },
                new Category() { ID = 4, Name = "Item 1.1", ParentID = 1 },
                new Category() { ID = 5, Name = "Item 3.1", ParentID = 3 },
                new Category() { ID = 6, Name = "Item 1.1.1", ParentID = 4 },
                new Category() { ID = 7, Name = "Item 2.1", ParentID = 2 }
            };
    
            List hierarchy = new List();                        
            hierarchy = categories
                            .Where(c => c.ParentID == 0)
                            .Select(c => new Category() { ID = c.ID, Name = c.Name, ParentID = c.ParentID, Children = GetChildren(categories, c.ID) })
                            .ToList();
    
            HieararchyWalk(hierarchy);            
    
            Console.ReadLine();
        }        
    
        public static List GetChildren(List categories, int parentId)
        {            
            return categories
                    .Where(c => c.ParentID == parentId)
                    .Select(c => new Category { ID = c.ID, Name = c.Name, ParentID = c.ParentID, Children = GetChildren(categories, c.ID) })
                    .ToList();
        }
    
        public static void HieararchyWalk(List hierarchy)
        {
            if (hierarchy != null)
            {
                foreach (var item in hierarchy)
                {
                    Console.WriteLine(string.Format("{0} {1}", item.ID, item.Name));
                    HieararchyWalk(item.Children);                    
                }
            }
        }        
    }
    

提交回复
热议问题