C#:树型数组,分级模糊查询

C#:树型数组,分级模糊查询

public class Data
        {
            public int id { get; set; }
            public int pid { get; set; }
            public string name { get; set; }
            public List children { get; set; }
        }
        static void Main(string[] args)
        {
            List obj = new List();
            obj.Add(new Data { id = 1, pid = 0, name = "a" });
            obj.Add(new Data { id = 2, pid = 1, name = "ab" });
            obj.Add(new Data { id = 3, pid = 1, name = "wa" });
            obj.Add(new Data { id = 4, pid = 2, name = "abc" });
            obj.Add(new Data { id = 5, pid = 3, name = "aw" });
            obj.Add(new Data { id = 6, pid = 1, name = "zz" });
            obj.Add(new Data { id = 7, pid = 2, name = "aa" });
            obj.Add(new Data { id = 8, pid = 3, name = "pw" });
            obj.Add(new Data { id = 9, pid = 3, name = "ap" });
            obj.Add(new Data { id = 10, pid = 1, name = "am" });
            obj.Add(new Data { id = 11, pid = 2, name = "sw" });
            obj.Insert(1, new Data { id = 8888, });
            Data li = new Data();
            li.id = 0;
            li.pid = 0;
            tolist(obj, li);
            var m = fun("b", li.children);
            Console.ReadLine();
        }
        /// 
        /// 树型数据模糊搜索
        /// 
        /// 
        /// 
        /// 
        public static List fun(string str, List list)
        {
            List ps = new List();
            foreach (var item in list)
            {
                if (item.name.Contains(str))
                {
                    item.children = item.children.Where(x => x.name.Contains(str)).ToList();
                    ps.Add(item);
                }
                else
                {
                    if (item.children.Count > 0 )
                    {
                        var li = fun(str, item.children);
                        Data obj = new Data
                        {
                            id = item.id,
                            name = item.name,
                            children = li,
                            pid = item.pid
                        };
                        if (li.Count() > 0 )
                        {
                            ps.Add(obj);
                        }
                    }
                }
            }
            return ps;
        }
        /// 
        /// 转树型
        /// 
        /// 
        /// 
        public static void tolist(List lists, Data p)
        {
            var list = lists.Where(ee => ee.pid == p.id).ToList();
            p.children = new List();
            p.children.AddRange(list);
            foreach (var item in list)
            {
                tolist(lists, item);
            }
        }

你可能感兴趣的:(C#:树型数组,分级模糊查询)