1.查询语法
Query Syntax:
from <range variable> in <IEnumerable<T> or IQueryable<T> Collection> <Standard Query Operators> <lambda expression> <select or groupBy operator> <result formation>
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
}; // LINQ Query Syntax
var result = from s in stringList
where s.Contains("Tutorials")
select s;
查询语法以From开头,后面紧跟着Range veriable变量,From从句像这样的结构"From rangeVariableName in IEnumerablecollection",意思是从集合的每个对象中获取,它有点像foreach循环,
foreach(Student s in studentList)
在From从句之后,我们可以使用不同的标准查询运算符来过滤、分类和联合集合里面的元素,大概有50个标准查询操作
一般以Select 或Group从句结尾,Select从句用来构建数据,你可以查询全部对象或者它的几个属性。
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = , StudentName = "John", Age = } ,
new Student() { StudentID = , StudentName = "Moin", Age = } ,
new Student() { StudentID = , StudentName = "Bill", Age = } ,
new Student() { StudentID = , StudentName = "Ram" , Age = } ,
new Student() { StudentID = , StudentName = "Ron" , Age = }
}; // LINQ Query Syntax to find out teenager students
var teenAgerStudent = from s in studentList
where s.Age > && s.Age <
select s;
LINQ Method Syntax
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
}; // LINQ Query Syntax
var result = stringList.Where(s => s.Contains("Tutorials"));
// Student collection
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = , StudentName = "John", Age = } ,
new Student() { StudentID = , StudentName = "Moin", Age = } ,
new Student() { StudentID = , StudentName = "Bill", Age = } ,
new Student() { StudentID = , StudentName = "Ram" , Age = } ,
new Student() { StudentID = , StudentName = "Ron" , Age = }
}; // LINQ Method Syntax to find out teenager students
var teenAgerStudents = studentList.Where(s => s.Age > && s.Age < )
.ToList<Student>();
Standard Query Operators:
Standard Query Operators in Query Syntax:
Standard Query Operators in Method Syntax:
标准查询操作根据功能分类
Filtering(筛选) | Where, OfType |
Sorting(排序) | OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse |
Grouping(分组) | GroupBy, ToLookup |
Join(连接) | GroupJoin, Join |
Projection(投影) | Select, SelectMany |
Aggregation(聚集) | Aggregate, Average, Count, LongCount, Max, Min, Sum |
Quantifiers(量词) | All, Any, Contains |
Elements(元素) | ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault |
Set(集合) | Distinct, Except, Intersect, Union |
Partitioning(分割) | Skip, SkipWhile, Take, TakeWhile |
Concatenation(连接) | Concat |
Equality | SequenceEqual |
Generation | DefaultEmpty, Empty, Range, Repeat |
Conversion | AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList |