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


Queryable.Where Метод

Определение

Фильтрует последовательность значений на основе предиката.

Перегрузки

Имя Описание
Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Фильтрует последовательность значений на основе предиката.

Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>)

Фильтрует последовательность значений на основе предиката. Индекс каждого элемента используется в логике функции предиката.

Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

Фильтрует последовательность значений на основе предиката.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TSource> ^ Where(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member Where : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> System.Linq.IQueryable<'Source>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member Where : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> System.Linq.IQueryable<'Source>
<Extension()>
Public Function Where(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As IQueryable(Of TSource)

Параметры типа

TSource

Тип элементов source.

Параметры

source
IQueryable<TSource>

Фильтруемая IQueryable<T> .

predicate
Expression<Func<TSource,Boolean>>

Функция для проверки каждого элемента для условия.

Возвращаемое значение

IQueryable<TSource>

Объект IQueryable<T> , содержащий элементы из входной последовательности, удовлетворяющей условию, заданному predicate.

Атрибуты

Исключения

source или predicate есть null.

Примеры

В следующем примере кода показано, как использовать Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) для фильтрации последовательности.

List<string> fruits =
    new List<string> { "apple", "passionfruit", "banana", "mango",
                       "orange", "blueberry", "grape", "strawberry" };

// Get all strings whose length is less than 6.
IEnumerable<string> query =
    fruits.AsQueryable().Where(fruit => fruit.Length < 6);

foreach (string fruit in query)
    Console.WriteLine(fruit);

/*
    This code produces the following output:

    apple
    mango
    grape
*/
Dim fruits As New List(Of String)(New String() _
                        {"apple", "passionfruit", "banana", "mango", _
                         "orange", "blueberry", "grape", "strawberry"})

' Get all strings whose length is less than 6.
Dim query = fruits.AsQueryable().Where(Function(fruit) fruit.Length < 6)

' Display the results.
Dim output As New System.Text.StringBuilder
For Each fruit As String In query
    output.AppendLine(fruit)
Next
MsgBox(output.ToString())

' This code produces the following output:

' apple
' mango
' grape

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) создает объект MethodCallExpression , представляющий Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает элементы из source этого условия, указанного в параметре predicate.

Применяется к

Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

Фильтрует последовательность значений на основе предиката. Индекс каждого элемента используется в логике функции предиката.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TSource> ^ Where(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, int, bool> ^> ^ predicate);
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,int,bool>> predicate);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,int,bool>> predicate);
static member Where : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, int, bool>> -> System.Linq.IQueryable<'Source>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member Where : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, int, bool>> -> System.Linq.IQueryable<'Source>
<Extension()>
Public Function Where(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Integer, Boolean))) As IQueryable(Of TSource)

Параметры типа

TSource

Тип элементов source.

Параметры

source
IQueryable<TSource>

Фильтруемая IQueryable<T> .

predicate
Expression<Func<TSource,Int32,Boolean>>

Функция для проверки каждого элемента для условия; Второй параметр функции представляет индекс элемента в исходной последовательности.

Возвращаемое значение

IQueryable<TSource>

Объект IQueryable<T> , содержащий элементы из входной последовательности, удовлетворяющей условию, заданному predicate.

Атрибуты

Исключения

source или predicate есть null.

Примеры

В следующем примере кода показано, как использовать Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>) фильтрацию последовательности на основе предиката, включающего индекс каждого элемента.

int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 };

// Get all the numbers that are less than or equal to
// the product of their index in the array and 10.
IEnumerable<int> query =
    numbers.AsQueryable()
    .Where((number, index) => number <= index * 10);

foreach (int number in query)
    Console.WriteLine(number);

/*
    This code produces the following output:

    0
    20
    15
    40
*/
Dim numbers() As Integer = {0, 30, 20, 15, 90, 85, 40, 75}

' Get all the numbers that are less than or equal to
' the product of their index in the array and 10.
Dim query = numbers.AsQueryable() _
    .Where(Function(number, index) number <= index * 10)

' Display the results.
Dim output As New System.Text.StringBuilder
For Each number As Integer In query
    output.AppendLine(number)
Next
MsgBox(output.ToString())

' This code produces the following output:

' 0
' 20
' 15
' 40

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>) создает объект MethodCallExpression , представляющий Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает элементы из source этого условия, указанного в параметре predicate. Индекс каждого исходного элемента предоставляется в качестве второго аргумента predicate.

Применяется к