1. 程式人生 > >LINQ 的select 和where 查詢語句總結

LINQ 的select 和where 查詢語句總結

1.SELECT語句

    (1) 普通查詢

         var list = from s in db.student select s.stuname;

    (2) 匿名類查詢

         var list = from c in db.customer select new {name = c.firstname+" "+c.lastname};

    (3) 條件查詢

         var list = from l in db.grade select new {name = l.name; level = l.score>60?"pass":"failed"};

    (4) 指定型別查詢

         var list = from e in db.card select new Name {first = e.firstname;last=e.lastname};

    (5) 篩選查詢

         var list = from s in db.student where s.id < 10 select s.name;

    (6) 匿名物件巢狀查詢

         var list = from e in db.data select new {

                                                                   company = new { companyname = e.name;

                                                                                               companyphone = e.phone},

                                                                   manager = e.manager;

                                                                    }

    (7)  呼叫方法查詢

         var list = from s in db.student select new {name=s.name,age=ageconvert(s.age)};

    (8) Distinct形式

         var list = (from s in db.student select s.name).distinct();

2. WHERE語句

    (1) 普通條件查詢

          var list = from s in db.student where s.name = "Jack" select s;

    (2) 關係條件查詢

         var list = from s in db.student where s.age>20 && s.sex ==1;

         var list = db.student.where(s=>s.age>20).where(s=>s.sex==1)

    (3) First形式(相當於SQL中Top(1))

         student stu = db.student.first(s=>s.age>20);