Queryable.First Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает первый элемент последовательности.
Перегрузки
| Имя | Описание |
|---|---|
| First<TSource>(IQueryable<TSource>) |
Возвращает первый элемент последовательности. |
| First<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) |
Возвращает первый элемент последовательности, удовлетворяющей указанному условию. |
First<TSource>(IQueryable<TSource>)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Возвращает первый элемент последовательности.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource First(System::Linq::IQueryable<TSource> ^ source);
public static TSource First<TSource>(this System.Linq.IQueryable<TSource> 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.")]
public static TSource First<TSource>(this System.Linq.IQueryable<TSource> source);
static member First : System.Linq.IQueryable<'Source> -> '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 First : System.Linq.IQueryable<'Source> -> 'Source
<Extension()>
Public Function First(Of TSource) (source As IQueryable(Of TSource)) As TSource
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IQueryable<TSource>
Возвращает IQueryable<T> первый элемент.
Возвращаемое значение
Первый элемент в source.
- Атрибуты
Исключения
source равно null.
Исходная последовательность пуста.
Примеры
В следующем примере кода показано, как использовать First<TSource>(IQueryable<TSource>) для возврата первого элемента в последовательности.
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 435, 67, 12, 19 };
int first = numbers.AsQueryable().First();
Console.WriteLine(first);
/*
This code produces the following output:
9
*/
Dim numbers() As Integer = {9, 34, 65, 92, 87, 435, 3, 54, _
83, 23, 87, 435, 67, 12, 19}
Dim first As Integer = numbers.AsQueryable().First()
MsgBox(first)
' This code produces the following output:
'
' 9
Комментарии
Метод First<TSource>(IQueryable<TSource>) создает объект MethodCallExpression , представляющий First<TSource>(IQueryable<TSource>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов First<TSource>(IQueryable<TSource>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает первый элемент в source.
Применяется к
First<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 TSource First(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static TSource First<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 TSource First<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member First : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> '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 First : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
<Extension()>
Public Function First(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As TSource
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IQueryable<TSource>
Объект IQueryable<T> , из который возвращается элемент.
- predicate
- Expression<Func<TSource,Boolean>>
Функция для проверки каждого элемента для условия.
Возвращаемое значение
Первый элемент, в source который проходит тест.predicate
- Атрибуты
Исключения
source или predicate есть null.
Элемент не удовлетворяет условию в predicate.
–или–
Исходная последовательность пуста.
Примеры
В следующем примере кода показано, как использовать First<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) для возврата первого элемента последовательности, удовлетворяющей условию.
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 435, 67, 12, 19 };
// Get the first number in the array that is greater than 80.
int first = numbers.AsQueryable().First(number => number > 80);
Console.WriteLine(first);
/*
This code produces the following output:
92
*/
Dim numbers() As Integer = {9, 34, 65, 92, 87, 435, 3, 54, _
83, 23, 87, 435, 67, 12, 19}
' Get the first number in the array that is greater than 80.
Dim first As Integer = numbers.AsQueryable().First(Function(number) number > 80)
MsgBox(first)
' This code produces the following output:
'
' 92
Комментарии
Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.
Метод First<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) создает объект MethodCallExpression , представляющий First<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов First<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает первый элемент, который source удовлетворяет условию, заданному predicate.