#region linq的标准查询运算符(即lambda方式) 注:C#不支持标准查询运算符中带有整形参数(索引)的重载
// 1、标准查询运算符之筛选方法——where
//IQueryable<Student> stu1=db.Student.Where(s => s.Ssex == "男");
//GridView1.DataSource = stu1;
//GridView1.DataBind();
// 2、标准查询运算符之select
//var stu2 =db.Student.Select(s => new {s.Sno,s.Sname,s.Sage}); //这叫匿名对象
//GridView2.DataSource = stu2;
//GridView2.DataBind();
//3、标准查询运算符之排序方法—— order
//升序排序
var stu3 = db.Student.OrderBy(s => s.Sage);
GridView1.DataSource = stu3;
GridView1.DataBind();
//降序排序之多条件排序
var stu4 = db.Student.OrderByDescending(s => s.Sage).ThenByDescending(s=>s.Sno);
GridView2.DataSource = stu4;
GridView2.DataBind();
//4、标准运算符之连接集合—— Join
var stu5 = db.Student.Join(db.StuCourse, s => s.Sno, stu => stu.Sno, (s, stu) => new { Sno=s.Sno,SCSno=stu.Sno,s.Sname,stu.Cid});
GridView2.DataSource = stu5;
GridView2.DataBind();
//左连接
var leftJoin = from stu in db.Student
join sc in db.StuCourse
on stu.Sno equals sc.Sno
into temp
from t in temp.DefaultIfEmpty()
select new { stu.Sno, stu.Sage, Cid = t == null ? 0 : t.Cid };
//右连接
var right = from sc in db.StuCourse
join stu in db.Student
on sc.Sno equals stu.Sno
into temp
from tt in temp.DefaultIfEmpty()
select new { sc.Cid, sc.Sno, SName = tt == null ? "" : tt.Sname };
//5、标准运算符之分组——GroupBy
//按照年龄分组
var stu6 = db.Student.GroupBy<Student, int>(s => (int)s.Sage);
List<IGrouping<int, Student>> list2 = stu6.ToList();
foreach (IGrouping<int,Student> item in list2)
{
//输出 小组 的 分组条件
Response.Write(string.Format("小组:{0}<br/>",item.Key));
//遍历 小组里 所有的 元素
foreach (Student st in item)
{
Response.Write(string.Format("姓名:{0}", st.Sname));
}
Response.Write("<br/>");
}
//6、标准运算符之分页数据——Skip + Take
//假设每页有5条记录
// int pageSize = 2;
//return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
var pageOne = db.Student.Skip<Student>(24).Take(6);
GridView1.DataSource = pageOne;
GridView1.DataBind();
#endregion
附加:
int[] numbers = { 0, 30, 15, 90, 85, 40, 75,20, };
int[] arr = { };
int first = numbers.First<int>(m => m > 35); // 返回满足条件的第一条记录 90
int last = numbers.Last<int>(n => n < 40); //返回满足条件的最后一条记录 20
bool allResult = numbers.All<int>(mm => mm < 100); //判断所有元素是否都满足 true
bool allResult2 = numbers.All<int>(mm => mm>5); // false
bool anyResult = numbers.Any(); //numbers中有元素 就返回 true
bool anyResult1 = arr.Any(); //arr中没有元素 返回false
bool anyResult2 = numbers.Any<int>(mm => mm <1); // 只要有一个元素满足条件 就返回true
bool anyResult3 = numbers.Any<int>(mm => mm >89); //true
bool anyResult5 = numbers.Any(m => m > 200); //false