Linq学習(join)

9062 ワード

<span style="font-size:14px;"> // 
    public class Stu
    {
        public int ID { set; get; } // 
        public string Name { set; get; } // 
        public int CourseId { set; get; } // id
    }
    // 
    public class Course
    {
        public int ID { set; get; } // 
        public string Cname { set; get; }// 

    }

 protected void Page_Load(object sender, EventArgs e)
        {
            List<Stu> list = new List<Stu> {
                
                new Stu { ID = 1001, Name = "zhangsan", CourseId=1},
                new Stu{ID=1002,Name="lisi", CourseId=2},
                new Stu{ID=1003,Name="wangwu", CourseId=3},
                 new Stu{ID=1004,Name="zhouliu", CourseId=1}
            
            };

            List<Course> clist = new List<Course>{
                 new Course{ ID=1,Cname="php"},
                 new Course{ID=3,Cname=".net"}
            };


        //  1. 


            var query = from a in list
                        join b in clist
                        on a.CourseId equals b.ID    // id, 
                        select new { a.Name, b.Cname };
            foreach (var item in query)
            {
                Response.Write(" : "+item.Name+"    : "+item.Cname+"<br/>");
            }

              //// : zhangsan  : php
            // : wangwu  : .net
            // : zhouliu  : php


        }

            // sql 
            var query = from a in list
                        join b in clist
                        on a.CourseId equals b.ID into hh
                        select new
                        {
                            sname = a.Name,
                            cname = hh
                        };
            foreach (var item in query)
            {
                Response.Write(item.sname + " :");
                foreach (var s in item.cname)
                {
                    Response.Write(s.Cname + ",");
                }
                Response.Write("<br/>");

            }
            // :
            //zhangsan :php,
            //lisi :
            //wangwu :.net,
            //zhouliu :php,</span>