排序
IEnumerable<Student> studentQuery = from student in students where student.Scores[0] > 90 orderby student.Last ascending select student;
ascending 升序排序,descending降序排序
分组
var studentQuery3 = from student in students group student by student.Last[0];
注:此查询没有按照字母进行排序。若要更改此功能,必须在group子句后提供orderby子句。但是,使用orderby子句,你首先需要,对group子句创建的组进行标识符的创建。使用into关键字,则提供此标识符
var studentQuery2 = from student in students group student by student.Last[0] into studentGroup orderby studentGroup.Key select studentGroup;
当运行此查询时,将爱那个会按照字母顺序排序。
使用let引入标识符
可以使用let关键字将任何表达式结果作为标识符引入到查询表达式。
在查询表达式中,存储子表达式的结果有时候很有用,这样可以在随后的子句中使用。可以使用let关键字完成这一工作。该关键字可以创建一个新的范围变量,并且用你提供的表达式的结果初始化该变量。一旦用值初始化了该范围变量,他就不能用于存储其他值。
可以通过存储表达式的结果提高性能。
var studentQuery5 = from student in students let totalScore = student.Scores[0] + student.Scores[1] + student.Scores[2] + student.Scores[3] where totalScore / 4 < student.Scores[0] select student.Last + " " + student.First; foreach (string s in studentQuery5) { Console.WriteLine(s); }
在查询表达式中使用方法语法
var studentQuery6 = from student in students let totalScore = student.Scores[0] + student.Scores[1] + student.Scores[2] + student.Scores[3] select totalScore; double averageScore = studentQuery6.Average(); Console.WriteLine("classs average score = {0}", averageScore);
通过average()方法计算班级平均分。
在select 子句中转换或投影
var studentQuery7 = from student in students let x = student.Scores[0] + student.Scores[1] + student.Scores[2] + student.Scores[3] where x > averageScore select new { id = student.ID, score = x }; foreach (var item in studentQuery7) { Console.WriteLine("Student ID :{0},Score:{1}",item.id,item.score); }