首页 > 代码库 > Linq学习(join)

Linq学习(join)

<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>

 

Linq学习(join)