Enumerable.ElementAt<TSource>(IEnumerable<TSource>, Int32) Metodo

Definizione

Restituisce l'elemento in corrispondenza di un indice specificato in una sequenza.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource ElementAt(System::Collections::Generic::IEnumerable<TSource> ^ source, int index);
public static TSource ElementAt<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int index);
static member ElementAt : seq<'Source> * int -> 'Source
<Extension()>
Public Function ElementAt(Of TSource) (source As IEnumerable(Of TSource), index As Integer) As TSource

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IEnumerable<TSource>

Oggetto IEnumerable<T> da cui restituire un elemento.

index
Int32

Indice in base zero dell'elemento da recuperare.

Valori restituiti

TSource

Elemento in corrispondenza della posizione specificata nella sequenza di origine.

Eccezioni

source è null.

index è minore di 0 o maggiore o uguale al numero di elementi in source.

Esempio

Nell'esempio di codice seguente viene illustrato come usare ElementAt per restituire un elemento in una posizione specifica.

string[] names =
    { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",

        "Hedlund, Magnus", "Ito, Shu" };
Random random = new Random(DateTime.Now.Millisecond);

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

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

/*
 This code produces output similar to the following:

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

Dim random As Random = New Random(DateTime.Now.Millisecond)

' Get a string at a random index within the array.
Dim name As String = names.ElementAt(random.Next(0, names.Length))

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

' This code produces output similar to the following:
'
' The name chosen at random is Ito, Shu

Commenti

Se il tipo di source implementa IList<T>, tale implementazione viene utilizzata per ottenere l'elemento in corrispondenza dell'indice specificato. In caso contrario, questo metodo ottiene l'elemento specificato.

Questo metodo genera un'eccezione se index non è compreso nell'intervallo. Per restituire invece un valore predefinito quando l'indice specificato non è compreso nell'intervallo, utilizzare il ElementAtOrDefault metodo .

Si applica a