Queryable.ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) Метод
Определение
Возвращает элемент последовательности по указанному индексу или значение по умолчанию, если индекс вне допустимого диапазона.Returns the element at a specified index in a sequence or a default value if the index is out of range.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource ElementAtOrDefault(System::Linq::IQueryable<TSource> ^ source, int index);
public static TSource ElementAtOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, int index);
public static TSource? ElementAtOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, int index);
static member ElementAtOrDefault : System.Linq.IQueryable<'Source> * int -> 'Source
<Extension()>
Public Function ElementAtOrDefault(Of TSource) (source As IQueryable(Of TSource), index As Integer) As TSource
Параметры типа
- TSource
Тип элементов source
.The type of the elements of source
.
Параметры
- source
- IQueryable<TSource>
Объект IQueryable<T>, из которого требуется возвратить элемент.An IQueryable<T> to return an element from.
- index
- Int32
Отсчитываемый от нуля индекс извлекаемого элемента.The zero-based index of the element to retrieve.
Возвращаемое значение
- TSource
default
(TSource
), если индекс index
находится вне source
; в противном случае элемент, находящийся в указанной позиции в последовательности source
.default
(TSource
) if index
is outside the bounds of source
; otherwise, the element at the specified position in source
.
Исключения
source
имеет значение null
.source
is null
.
Примеры
В следующем примере кода демонстрируется использование метода ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32).The following code example demonstrates how to use ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32). В этом примере используется значение для index
, находящееся за границами исходной последовательности.This example uses a value for index
that is outside the bounds of the source sequence.
string[] names = { "Hartono, Tommy", "Adams, Terry",
"Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
int index = 20;
string name = names.AsQueryable().ElementAtOrDefault(index);
Console.WriteLine(
"The name chosen at index {0} is '{1}'.",
index,
String.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name);
/*
This code produces the following output:
The name chosen at index 20 is '[NONE AT THIS INDEX]'.
*/
Dim names() As String = {"Hartono, Tommy", "Adams, Terry", _
"Andersen, Henriette Thaulow", _
"Hedlund, Magnus", "Ito, Shu"}
Dim index As Integer = 20
Dim name As String = names.AsQueryable().ElementAtOrDefault(index)
MsgBox(String.Format("The name at index {0} is '{1}'.", _
index, IIf(String.IsNullOrEmpty(name), "[NONE AT THIS INDEX]", name)))
' This code produces the following output:
'
' The name at index 20 is '[NONE AT THIS INDEX]'.
Комментарии
ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32)Метод создает объект MethodCallExpression , который представляет вызов ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) самого себя как сконструированного универсального метода.The ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) method generates a MethodCallExpression that represents calling ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) itself as a constructed generic method. Затем он передает MethodCallExpression Execute<TResult>(Expression) методу класса, IQueryProvider представленного Provider свойством source
параметра.It then passes the MethodCallExpression to the Execute<TResult>(Expression) method of the IQueryProvider represented by the Provider property of the source
parameter.
Поведение запроса, которое происходит в результате выполнения дерева выражения, представляющего вызов, ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) зависит от реализации типа source
параметра.The query behavior that occurs as a result of executing an expression tree that represents calling ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) depends on the implementation of the type of the source
parameter. Ожидаемое поведение заключается в том, что он возвращает элемент в позиции index
в source
, или default(TSource)
index
, если находится за пределами границ source
.The expected behavior is that it returns the item at position index
in source
, or default(TSource)
if index
is outside the bounds of source
.