LINQ获取树结构数据且赋值给model

bijiayue 2017-03-14 03:56:11

表是这样的,用linq取出全部赋值给model是model达到以下效果


求大神给出实现代码,或者范例
...全文
1130 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
无限递归啊啊
bijiayue 2017-03-15
  • 打赏
  • 举报
回复
最好用LINQ 递归加迭代器的方式,要实现无限生成

我写了一个方法,但是测试是,没有进入方法也没报错,问下大神们错误在哪里
ches


正怒月神 2017-03-14
  • 打赏
  • 举报
回复
递归方法
static void Main(string[] args)
        {
            //调用
            Create(ur,0);
            //打印
            Print(ur);

            Console.ReadLine();
        }
        //测试数据
        static List<User> list = new List<User>()
            {
                new User(){id=1,name="food",parentId=0},
                new User(){id=2,name="fruit",parentId=1},
                new User(){id=3,name="red",parentId=2},
                new User(){id=4,name="cherry",parentId=3},
                new User(){id=5,name="yellow",parentId=2},
                new User(){id=6,name="banana",parentId=5},
                new User(){id=7,name="meat",parentId=1},
                new User(){id=8,name="beef",parentId=7},
                new User(){id=9,name="pork",parentId=7},
            };

        //最终结果
        static UserR ur = new UserR();

        //递归遍历
        private static void Create(UserR node, int id)
        {
            var q = list.Where(x => x.parentId == id).ToList();
            if (id == 0)                                  // id = 0 是根节点   
            {
                for (int i = 0; i < q.Count; i++)
                {
                    UserR nd = new UserR();
                    nd.id = q[i].id;
                    nd.name = q[i].name;
                    Create(nd, q[i].id);
                    ur.u.Add(nd);
                }
            }
            else
            {
                for (int i = 0; i < q.Count; i++)
                {
                    UserR Tnode = new UserR();
                    Tnode.id = q[i].id;
                    Tnode.name = q[i].name;
                    Create(Tnode, q[i].id);
                    node.u.Add(Tnode);
                }
            }
        }

        //打印查看结果
        static void Print(UserR ur)
        {
            Console.WriteLine(ur.name);
            if(ur.u!=null)
                foreach (var item in ur.u)
                {
                    Print(item);
                }
        }

        //查询出的实体层
        public class User
        {
            public int id { get; set; }
            public string name { get; set; }
            public int parentId { get; set; }
        }
        //遍历后的实体层
        public class UserR
        {
            public int id { get; set; }
            public string name { get; set; }
            public List<UserR> u = new List<UserR>();
            public int parentId { get; set; }
        }

8,497

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧