本主题演示在 C# 中编写 LINQ 查询的三种方式:
-
使用查询语法。
-
使用方法语法。
-
组合使用查询语法和方法语法。
下面的示例使用前面列出的每种方式演示一些简单的 LINQ 查询。 一般的规则是尽可能使用 (1),而在必要时使用 (2) 和 (3)。
编写大多数查询的推荐方式是使用查询语法来创建查询表达式。 下面的示例演示了三个查询表达式。 第一个查询表达式演示如何通过用 where 子句应用条件来筛选或限制结果, 它返回源序列中值大于 7 或小于 3 的所有元素。 第二个表达式演示如何对返回的结果进行排序。 第三个表达式演示如何按照键对结果进行分组, 此查询可根据单词的第一个字母返回两个组。
// Query #1. List<int> numbers = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query variable can also be implicitly typed by using var IEnumerable<int> filteringQuery = from num in numbers where num < 3 || num > 7 select num; // Query #2. IEnumerable<int> orderingQuery = from num in numbers where num < 3 || num > 7 orderby num ascending select num; // Query #3. string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" }; IEnumerable<IGrouping<char, string>> queryFoodGroups = from item in groupingQuery group item by item[0];
某些查询操作必须表示为方法调用。 最常见的此类方法是那些返回单一数值的方法,如 Sum、Max、Min、Average 等。 这些方法在任何查询中都必须总是最后调用,因为它们仅表示单个值,不能充当其他查询操作的数据源。 下面的示例演示查询表达式中的方法调用:
List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; List<int> numbers2 = new List<int>() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 }; // Query #4. double average = numbers1.Average(); // Query #5. IEnumerable<int> concatenationQuery = numbers1.Concat(numbers2);
此示例演示如何对查询子句的结果使用方法语法。 只需将查询表达式括在括号内,然后应用点运算符并调用此方法。 在下面的示例中,查询 7 返回其值在 3 和 7 之间的数字个数。 但是,通常更好的做法是使用另一个变量来存储方法调用的结果。 这样就不太容易将查询本身与查询结果相混淆。
// Query #7. // Using a query expression with method syntax int numCount1 = (from num in numbers1 where num < 3 || num > 7 select num).Count(); // Better: Create a new variable to store // the method call result IEnumerable<int> numbersQuery = from num in numbers1 where num < 3 || num > 7 select num; int numCount2 = numbersQuery.Count();