英語で読む

次の方法で共有


Enumerable.ElementAtOrDefault メソッド

定義

オーバーロード

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index)

シーケンス内の指定したインデックス位置にある要素を返します。インデックスが範囲外の場合は既定値を返します。

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32)

シーケンス内の指定したインデックス位置にある要素を返します。インデックスが範囲外の場合は既定値を返します。

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index)

ソース:
ElementAt.cs
ソース:
ElementAt.cs
ソース:
ElementAt.cs

シーケンス内の指定したインデックス位置にある要素を返します。インデックスが範囲外の場合は既定値を返します。

C#
public static TSource? ElementAtOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Index index);

型パラメーター

TSource

source の要素の型。

パラメーター

source
IEnumerable<TSource>

返される要素が含まれる IEnumerable<T>

index
Index

取得する要素のインデックス 。シーケンスの先頭または末尾のいずれかです。

戻り値

TSource

default がシーケンスの境界外にある場合 index は 。それ以外の source 場合は、シーケンス内の指定した位置にある source 要素。

例外

sourcenull です。

注釈

source 型が を実装する IList<T>場合、その実装は、指定したインデックス位置にある要素を取得するために使用されます。 それ以外の場合、このメソッドは指定した要素を取得します。

参照型と null 許容型の既定値は です null

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET 6, 7, 8, 9

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32)

ソース:
ElementAt.cs
ソース:
ElementAt.cs
ソース:
ElementAt.cs

シーケンス内の指定したインデックス位置にある要素を返します。インデックスが範囲外の場合は既定値を返します。

C#
public static TSource ElementAtOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int index);
C#
public static TSource? ElementAtOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int index);

型パラメーター

TSource

source の要素の型。

パラメーター

source
IEnumerable<TSource>

返される要素が含まれる IEnumerable<T>

index
Int32

取得する要素の、0 から始まるインデックス。

戻り値

TSource

インデックスがソース シーケンスの範囲外の場合は default (TSource)。それ以外の場合は、ソース シーケンスの指定した位置にある要素。

例外

sourcenullです。

ElementAtOrDefault を使用する方法を次のコード例に示します。 この例では、配列の境界外にあるインデックスを使用します。

C#
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>'.
*/

注釈

source 型が を実装する IList<T>場合、その実装は、指定したインデックス位置にある要素を取得するために使用されます。 それ以外の場合、このメソッドは指定した要素を取得します。

参照型と null 許容型の既定値は です null

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0