Enumerable.ElementAtOrDefault<TSource>(IEnumerable<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::Collections::Generic::IEnumerable<TSource> ^ source, int index);
public static TSource ElementAtOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int index);
static member ElementAtOrDefault : seq<'Source> * int -> 'Source
<Extension()>
Public Function ElementAtOrDefault(Of TSource) (source As IEnumerable(Of TSource), index As Integer) As TSource

类型参数

TSource

source 的元素类型。The type of the elements of source.

参数

source
IEnumerable<TSource>

要从中返回元素的 IEnumerable<T>An IEnumerable<T> to return an element from.

index
Int32

要检索的从零开始的元素索引。The zero-based index of the element to retrieve.

返回

TSource

如果索引超出源序列的边界,则为 default(TSource);否则为源序列中指定位置处的元素。default(TSource) if the index is outside the bounds of the source sequence; otherwise, the element at the specified position in the source sequence.

例外

sourcenullsource is null.

示例

下面的代码示例演示如何使用 ElementAtOrDefaultThe following code example demonstrates how to use ElementAtOrDefault. 此示例使用超出数组界限的索引。This example uses an index that is outside the bounds of the array.

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

int index = 20;

string name = names.ElementAtOrDefault(index);

Console.WriteLine(
    "The name chosen at index {0} is '{1}'.",
    index,
    String.IsNullOrEmpty(name) ? "<no name at this index>" : name);

/*
 This code produces the following output:

 The name chosen at index 20 is '<no name at this index>'.
*/
' Create an array of strings.
Dim names() As String =
{"Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu"}

Dim index As Integer = 20

' Get a string at an index that is out of range in the array.
Dim name As String = names.ElementAtOrDefault(index)

Dim text As String = If(String.IsNullOrEmpty(name), "[THERE IS NO NAME AT THIS INDEX]", name)

' Display the output.
Console.WriteLine($"The name chosen at index {index} is {text}")

' This code produces the following output:
'
' The name chosen at index 20 is [THERE IS NO NAME AT THIS INDEX]

注解

如果 source 的类型实现 IList<T>,则该实现用于获取指定索引处的元素。If the type of source implements IList<T>, that implementation is used to obtain the element at the specified index. 否则,此方法将获取指定的元素。Otherwise, this method obtains the specified element.

引用和可以为 null 的类型的默认值为 nullThe default value for reference and nullable types is null.

适用于