类型 查询变量 = from 临时变量in 集合对象或数据库对象
[where 条件表达式]
[order by 条件]
select 临时变量中被查询的值
[group by 条件]
- 简单的查询
var movies = from c in db.movies
select c; //此处是一个集合
sql : select * from db.movies
2. 带where 条件的查询
movies = movies.Where(w =>w.ID>10);
sql :select * from movies where ID>10
3. 排序order by desc/asc
var ss = from r in db.movies where r.ID > 10
orderby r.ID descending //倒序 //
orderby r.ID ascending //正序 select r; //正序
var ss1 = db.movies .OrderBy(p => p.ID).Where(p => p.ID> 10).ToList(); //倒序
var ss2 = db.movies .OrderByDescending(p => p.ID).Where(p => p.ID> 10).ToList();
sql : select * from movies where ID>10 order by ID desc; // or asc
4.top
//如果取最后一个可以按倒叙排列再取值
var ss = (from r in db.movies
select r).FirstOrDefault();
var ss1 = db.movies .FirstOrDefault();
//var ss1 = db.movies .First();
sql = select top(1) * from movies ;
5.包含,类似 like
var ss = from r in db.movies
where r.SortsText.Contains("张")
select r;
var aa= db.movies .Where(p => p.Title.Contains("张")).ToList();
sql = select * from movies where Title like '%张%';
6.连接查询
var bb= from r in db.movies
join w in db.movies2 on r.VID equals w.MID
orderby r.VID descending
select r;
var aa = db.movies .Join(db.movies2 , p => p.VID , r => r.VID , (p, r) => p).OrderByDescending(p => p.VID ).ToList();
sql = select r.* from movies as r inner join dbo.movies2 as t on r.VID = t.MID order by r.VID desc;
7.sql IN
var aa= from p in db.movies
where (new int?[] { 24, 25,26 }).Contains(p.VID )
select p;
foreach (var p in ss)
{
Response.Write(p.Sorts);
}
sql = select * from movies where VID in(24,25,26);