Share via


筛选数据

筛选指将结果集限制为只包含那些满足指定条件的元素的操作。 它又称为选择。

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

LINQ 筛选操作

下面一节中列出了执行选择的标准查询运算符方法。

方法

方法名

说明

C# 查询表达式语法

Visual Basic 查询表达式语法

更多信息

OfType

根据值强制转换为指定类型的能力选择值。

不适用。

不适用。

Enumerable.OfType<TResult>

Queryable.OfType<TResult>

Where

选择基于谓词函数的值。

where

Where

Enumerable.Where

Queryable.Where

查询表达式语法示例

下面的示例使用 where 子句(在 C# 中)或 Where 子句(在 Visual Basic 中)来从数组中筛选那些具有特定长度的字符串。


        Dim words() As String = {"the", "quick", "brown", "fox", "jumps"}

        Dim query = From word In words 
                    Where word.Length = 3 
                    Select word

        Dim sb As New System.Text.StringBuilder()
        For Each str As String In query
            sb.AppendLine(str)
        Next

        ' Display the results.
        MsgBox(sb.ToString())

        ' This code produces the following output:

        ' the
        ' fox


            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
            */

请参见

任务

如何:在运行时动态指定谓词筛选器(C# 编程指南)

如何:使用 LINQ 筛选查询结果 (Visual Basic)

如何:使用反射查询程序集的元数据 (LINQ)

如何:查询具有指定特性或名称的文件

如何:按任意词或字段对文本数据进行排序或筛选 (LINQ)

参考

where 子句(C# 参考)

Where 子句 (Visual Basic)

System.Linq

概念

标准查询运算符概述