筛选是指限制结果集只包含满足指定条件的元素的作。 也称作 选择 匹配指定条件的元素。
重要
这些示例使用 System.Collections.Generic.IEnumerable<T> 数据源。 基于System.Linq.IQueryProvider的数据源使用System.Linq.IQueryable<T> 数据源和表达式树。 表达式树对允许的 C# 语法有 限制 。 此外,每个 IQueryProvider
数据源(如 EF Core )可能会施加更多的限制。 查看数据源的文档。
下图显示了筛选字符序列的结果。 筛选操作的谓词要求字符必须为“A”。
下表列出了执行选择的标准查询运算符方法:
方法名 | DESCRIPTION | C# 查询表达式语法 | 详细信息 |
---|---|---|---|
OfType | 根据其转换为特定类型的能力选择值。 | 不適用。 | Enumerable.OfType Queryable.OfType |
位置 | 选择基于谓词函数的值。 | where |
Enumerable.Where Queryable.Where |
以下示例使用 where
子句从具有特定长度的字符串的数组中进行筛选。
string[] words = ["the", "quick", "brown", "fox", "jumps"];
IEnumerable<string> query = from word in words
where word.Length == 3
select word;
foreach (string str in query)
{
Console.WriteLine(str);
}
/* This code produces the following output:
the
fox
*/
以下代码显示了使用方法语法的等效查询:
string[] words = ["the", "quick", "brown", "fox", "jumps"];
IEnumerable<string> query =
words.Where(word => word.Length == 3);
foreach (string str in query)
{
Console.WriteLine(str);
}
/* This code produces the following output:
the
fox
*/