Поделиться через


Filtering Data

Filtering refers to the operation of restricting the result set to contain only those elements that satisfy a specified condition. It is also known as selection.

The following illustration shows the results of filtering a sequence of characters. The predicate for the filtering operation specifies that the character must be 'A'.

LINQ Filtering Operation

The standard query operator methods that perform selection are listed in the following section.

Methods

Method Name

Description

C# Query Expression Syntax

Visual Basic Query Expression Syntax

More Information

OfType

Selects values, depending on their ability to be cast to a specified type.

Not applicable.

Not applicable.

Enumerable.OfType<TResult>

Queryable.OfType<TResult>

Where

Selects values that are based on a predicate function.

where

Where

Enumerable.Where

Queryable.Where

Query Expression Syntax Example

The following example uses the where clause in C# or the Where clause in Visual Basic to filter from an array those strings that have a specific length.


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

See Also

Tasks

How to: Dynamically Specify Predicate Filters at Runtime (C# Programming Guide)

How to: Filter Query Results by Using LINQ (Visual Basic)

How to: Query An Assembly's Metadata with Reflection (LINQ)

How to: Query for Files with a Specified Attribute or Name

How to: Sort or Filter Text Data by Any Word or Field (LINQ)

Reference

where clause (C# Reference)

Where Clause (Visual Basic)

System.Linq

Concepts

Standard Query Operators Overview