使用 LINQ 筛选 C# 中的数据

筛选是指将结果集限制为仅包含满足指定条件的元素的操作。 它也称为“选择”与指定条件匹配的元素。

下图演示了对字符序列进行筛选的结果。 筛选操作的谓词指定字符必须为“A”。

显示 LINQ 筛选操作的图表

下表中列出了执行选择的标准查询运算符方法:

方法名 描述 C# 查询表达式语法 详细信息
OfType 根据其转换为特定类型的能力选择值。 不适用。 Enumerable.OfType

Queryable.OfType
Where 选择基于谓词函数的值。 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
*/

另请参阅