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


Queryable.ElementAt Метод

Определение

Перегрузки

Имя Описание
ElementAt<TSource>(IQueryable<TSource>, Index)

Возвращает элемент по указанному индексу в последовательности.

ElementAt<TSource>(IQueryable<TSource>, Int32)

Возвращает элемент по указанному индексу в последовательности.

ElementAt<TSource>(IQueryable<TSource>, Index)

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

Возвращает элемент по указанному индексу в последовательности.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource ElementAt(System::Linq::IQueryable<TSource> ^ source, Index index);
public static TSource ElementAt<TSource>(this System.Linq.IQueryable<TSource> source, Index index);
[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 ElementAt<TSource>(this System.Linq.IQueryable<TSource> source, Index index);
static member ElementAt : System.Linq.IQueryable<'Source> * Index -> '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 ElementAt : System.Linq.IQueryable<'Source> * Index -> 'Source
<Extension()>
Public Function ElementAt(Of TSource) (source As IQueryable(Of TSource), index As Index) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

Объект IQueryable<T> , из который возвращается элемент.

index
Index

Индекс извлекаемого элемента, который находится в начале или конце.

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

TSource

Элемент в указанной source позиции в последовательности.

Атрибуты

Исключения

source равно null.

index находится вне границ source последовательности.

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

ElementAt<TSource>(IQueryable<TSource>, Int32)

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

Возвращает элемент по указанному индексу в последовательности.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource ElementAt(System::Linq::IQueryable<TSource> ^ source, int index);
public static TSource ElementAt<TSource>(this System.Linq.IQueryable<TSource> source, int index);
[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 ElementAt<TSource>(this System.Linq.IQueryable<TSource> source, int index);
static member ElementAt : System.Linq.IQueryable<'Source> * int -> '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 ElementAt : System.Linq.IQueryable<'Source> * int -> 'Source
<Extension()>
Public Function ElementAt(Of TSource) (source As IQueryable(Of TSource), index As Integer) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

Объект IQueryable<T> , из который возвращается элемент.

index
Int32

Отсчитываемый от нуля индекс элемента.

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

TSource

Элемент в указанной позиции sourceв .

Атрибуты

Исключения

source равно null.

index меньше нуля.

Примеры

В следующем примере кода показано, как использовать ElementAt<TSource>(IQueryable<TSource>, Int32) для возврата элемента в определенной позиции в последовательности.

string[] names = { "Hartono, Tommy", "Adams, Terry",
                   "Andersen, Henriette Thaulow",
                   "Hedlund, Magnus", "Ito, Shu" };

Random random = new Random(DateTime.Now.Millisecond);

string name =
    names.AsQueryable().ElementAt(random.Next(0, names.Length));

Console.WriteLine("The name chosen at random is '{0}'.", name);

/*
    This code produces the following sample output.
    Yours may be different due to the use of Random.

    The name chosen at random is 'Ito, Shu'.
*/
Dim names() As String = {"Hartono, Tommy", "Adams, Terry", _
                   "Andersen, Henriette Thaulow", _
                   "Hedlund, Magnus", "Ito, Shu"}

Dim rand As New Random(DateTime.Now.Millisecond)

Dim name As String = _
    names.AsQueryable().ElementAt(rand.Next(0, names.Length))

MsgBox(String.Format("The name chosen at random is '{0}'.", name))

' This code produces the following sample output.
' Yours may be different due to the use of Random.
'
' The name chosen at random is 'Ito, Shu'.

Комментарии

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

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

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