LINQ(语言集成查询)常用查询语句

LINQ 查询语法

有两种将LINQ查询写入 IEnumerable 集合 或 IQueryable数据源的基本方法。

  1. 查询语法或查询表达式语法
  2. 方法语法或方法扩展语法或连贯语法

查询语法

查询语法类似于数据库的SQL(结构化查询语言)。它在C#或VB代码中定义。

LINQ查询语法:

1
2
3
4
5
from <range variable> in <IEnumerable<T> or IQueryable<T> Collection>

<Standard Query Operators> <lambda expression>

<select or groupBy operator> <result formation>

LINQ查询语法以from关键字开头,以select关键字结尾。下面是一个示例LINQ查询,该查询返回一个字符串集合,其中包含一个单词“ Tutorials”。

示例:C#中的LINQ查询语法

1
2
3
4
5
6
7
8
9
10
11
12
13
// 字符串集合
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ查询语法
var result = from s in stringList
where s.Contains("Tutorials")
select s;

LINQ查询语法

查询语法以 From 子句开头,后跟 Range 变量。From 子句的结构类似于“ From rangeVariableName in i enumerablecollection”。在英语中,这意味着,从集合中的每个对象。它类似于 foreach 循环:foreach(Student s in studentList)。

在FROM子句之后,可以使用不同的标准查询运算符来过滤,分组和联接集合中的元素。LINQ中大约有50个标准查询运算符。在上图中,我们使用了“ where”运算符(又称子句),后跟一个条件。通常使用lambda表达式来表达此条件。

LINQ查询语法始终以Select或Group子句结尾。Select子句用于整形数据。您可以按原样选择整个对象,也可以仅选择某些属性。在上面的示例中,我们选择了每个结果字符串元素。

在下面的示例中,我们使用LINQ查询语法从Student集合(序列)中找出青少年学生。

示例:C#中的LINQ查询语法

1
2
3
4
5
6
7
8
9
10
11
12
13
// 学生集合
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

// LINQ查询语法找出青少年学生
var teenAgerStudent = from s in studentList
where s.Age > 12 && s.Age < 20
select s;

示例:VB.Net中的LINQ查询语法

1
2
3
4
5
6
7
8
9
10
11
12
13
// 学生集合
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}

// LINQ查询语法找出青少年学生
Dim teenAgerStudents As IList(Of Student) = (From s In studentList _
Where s.Age > 12 And s.Age < 20 _
Select s).ToList()

要记住的要点

  1. 顾名思义,查询语法与SQL(结构查询语言)语法相同。
  2. 查询语法以from子句开头,可以以SelectGroupBy子句结尾。
  3. 使用各种其他运算符,例如过滤,联接,分组,排序运算符来构造所需的结果。
  4. 隐式类型变量-var可用于保存LINQ查询的结果。