子 where 句在查询表达式中使用,以指定数据源中的哪些元素将在查询表达式中返回。 它将布尔条件(谓词)应用于每个源元素(由范围变量引用),并返回指定条件为 true 的元素。 单个查询表达式可能包含多个 where 子句,单个子句可能包含多个谓词子表达式。
示例 1
在以下示例中,子 where 句筛选掉除小于 5 的数字之外的所有数字。 如果删除该 where 子句,将返回数据源中的所有数字。 表达式 num < 5 是应用于每个元素的谓词。
class WhereSample
{
static void Main()
{
// Simple data source. Arrays support IEnumerable<T>.
int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];
// Simple query with one predicate in where clause.
var queryLowNums =
from num in numbers
where num < 5
select num;
// Execute the query.
foreach (var s in queryLowNums)
{
Console.Write(s.ToString() + " ");
}
}
}
//Output: 4 1 3 2 0
示例 2
在单个 where 子句中,可以使用 && 和 || 运算符根据需要指定任意数量的谓词。 在下面的示例中,查询指定两个谓词,以便仅选择小于 5 的偶数。
class WhereSample2
{
static void Main()
{
// Data source.
int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];
// Create the query with two predicates in where clause.
var queryLowNums2 =
from num in numbers
where num < 5 && num % 2 == 0
select num;
// Execute the query
foreach (var s in queryLowNums2)
{
Console.Write(s.ToString() + " ");
}
Console.WriteLine();
// Create the query with two where clause.
var queryLowNums3 =
from num in numbers
where num < 5
where num % 2 == 0
select num;
// Execute the query
foreach (var s in queryLowNums3)
{
Console.Write(s.ToString() + " ");
}
}
}
// Output:
// 4 2 0
// 4 2 0
示例 3
子 where 句可能包含返回布尔值的一个或多个方法。 在下面的示例中,子 where 句使用一种方法来确定范围变量的当前值是偶数还是奇数。
class WhereSample3
{
static void Main()
{
// Data source
int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];
// Create the query with a method call in the where clause.
// Note: This won't work in LINQ to SQL unless you have a
// stored procedure that is mapped to a method by this name.
var queryEvenNums =
from num in numbers
where IsEven(num)
select num;
// Execute the query.
foreach (var s in queryEvenNums)
{
Console.Write(s.ToString() + " ");
}
}
// Method may be instance method or static method.
static bool IsEven(int i) => i % 2 == 0;
}
//Output: 4 8 6 2 0
注解
子 where 句是筛选机制。 它几乎可以在查询表达式中的任何位置定位,但不能是第一个或最后一个子句。 子 where 句可能出现在 组 子句之前或之后,具体取决于是必须在对源元素进行分组之前还是之后筛选源元素。
如果指定的谓词对数据源中的元素无效,则会导致编译时错误。 这是 LINQ 提供的强类型检查的一个好处。
在编译时, where 关键字转换为对标准查询运算符方法的 Where 调用。