C# 获取 父类和子类的集合

来源:互联网 发布:网络犯罪的案例 编辑:程序博客网 时间:2024/05/20 10:20
class Program    {        static void Main(string[] args)        {            List<Category> category = new List<Category>();            SqlConnection conn = new SqlConnection("Data Source=PC2010052713WQF//SQLEXPRESS;Initial Catalog=testSql;Integrated Security=SSPI;");            SqlCommand cmd = new SqlCommand("select * from Category", conn);            conn.Open();            SqlDataReader reder = cmd.ExecuteReader();            while (reder.Read())            {                Category cate = new Category()                {                    Id = Convert.ToInt32(reder["id"]),                    name = reder["name"].ToString(),                    pid = Convert.ToInt32(reder["pid"])                };                category.Add(cate);            }            conn.Close();            foreach (Category cates in category)            {                cates.prent = category.FirstOrDefault(p => p.Id == cates.pid);                cates.ChildList = category.Where(p => p.pid == cates.Id).ToList();            }        }    }    class Category    {        public int Id { get; set; }        public string name { get; set; }        public Category prent { get; set; }        public int pid { get; set; }        public List<Category> ChildList { get; set; }    }