Enumerable.LastOrDefault Metodo

Definizione

Restituisce l’ultimo elemento di una sequenza o un valore predefinito se non viene trovato alcun elemento.

Overload

LastOrDefault<TSource>(IEnumerable<TSource>)

Restituisce l'ultimo elemento di una sequenza o un valore predefinito se la sequenza non contiene elementi.

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

Restituisce l'ultimo elemento di una sequenza che soddisfa una condizione specificata o un valore predefinito se tale elemento non viene trovato.

LastOrDefault<TSource>(IEnumerable<TSource>, TSource)

Restituisce l'ultimo elemento di una sequenza o un valore predefinito specificato se la sequenza non contiene elementi.

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

Restituisce l'ultimo elemento di una sequenza che soddisfa una condizione o un valore predefinito specificato se non viene trovato alcun elemento di questo tipo.

LastOrDefault<TSource>(IEnumerable<TSource>)

Restituisce l'ultimo elemento di una sequenza o un valore predefinito se la sequenza non contiene elementi.

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

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IEnumerable<TSource>

Oggetto IEnumerable<T> di cui restituire l’ultimo elemento.

Restituisce

TSource

default(TSource) se la sequenza di origine è vuota; in caso contrario, l'ultimo elemento in IEnumerable<T>.

Eccezioni

source è null.

Esempio

Nell'esempio di codice seguente viene illustrato come usare LastOrDefault<TSource>(IEnumerable<TSource>) in una matrice vuota.

string[] fruits = { };
string last = fruits.LastOrDefault();
Console.WriteLine(
    String.IsNullOrEmpty(last) ? "<string is null or empty>" : last);

/*
 This code produces the following output:

 <string is null or empty>
*/
' Create an empty array.
Dim fruits() As String = {}

' Get the last item in the array, or a
' default value if there are no items.
Dim last As String = fruits.LastOrDefault()

' Display the result.
Console.WriteLine(IIf(String.IsNullOrEmpty(last),
       "<string is Nothing or empty>",
       last))

' This code produces the following output:
'
' <string is Nothing or empty>

A volte il valore di default(TSource) non è il valore predefinito che si vuole usare se la raccolta non contiene elementi. Anziché controllare il risultato per il valore predefinito indesiderato e modificarlo, se necessario, è possibile usare il metodo per specificare il DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) valore predefinito che si vuole usare se la raccolta è vuota. Chiamare Last<TSource>(IEnumerable<TSource>) quindi per ottenere l'ultimo elemento. Nell'esempio di codice seguente vengono usate entrambe le tecniche per ottenere un valore predefinito pari a 1 se una raccolta di giorni numerici del mese è vuota. Poiché il valore predefinito per un intero è 0, che non corrisponde a un giorno del mese, il valore predefinito deve essere specificato come 1. La prima variabile di risultato viene controllata per il valore predefinito indesiderato dopo il completamento dell'esecuzione della query. La seconda variabile di risultato viene ottenuta usando DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) per specificare un valore predefinito pari a 1.

List<int> daysOfMonth = new List<int> { };

// Setting the default value to 1 after the query.
int lastDay1 = daysOfMonth.LastOrDefault();
if (lastDay1 == 0)
{
    lastDay1 = 1;
}
Console.WriteLine("The value of the lastDay1 variable is {0}", lastDay1);

// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int lastDay2 = daysOfMonth.DefaultIfEmpty(1).Last();
Console.WriteLine("The value of the lastDay2 variable is {0}", lastDay2);

/*
 This code produces the following output:

 The value of the lastDay1 variable is 1
 The value of the lastDay2 variable is 1
*/
Dim daysOfMonth As New List(Of Integer)(New Integer() {})

' Setting the default value to 1 after the query.
Dim lastDay1 As Integer = daysOfMonth.LastOrDefault()
If lastDay1 = 0 Then
    lastDay1 = 1
End If
Console.WriteLine($"The value of the lastDay1 variable is {lastDay1}")

' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim lastDay2 As Integer = daysOfMonth.DefaultIfEmpty(1).Last()
Console.WriteLine($"The value of the lastDay2 variable is {lastDay2}")

' This code produces the following output:
'
' The value of the lastDay1 variable is 1
' The value of the lastDay2 variable is 1

Commenti

Il valore predefinito per i tipi di riferimento e nullable è null.

Il LastOrDefault metodo non fornisce un modo per specificare un valore predefinito. Se si vuole specificare un valore predefinito diverso da default(TSource), usare il DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) metodo come descritto nella sezione Esempio.

Si applica a

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

Restituisce l'ultimo elemento di una sequenza che soddisfa una condizione specificata o un valore predefinito se tale elemento non viene trovato.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource LastOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate);
public static TSource LastOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
public static TSource? LastOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
static member LastOrDefault : seq<'Source> * Func<'Source, bool> -> 'Source
<Extension()>
Public Function LastOrDefault(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean)) As TSource

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IEnumerable<TSource>

Oggetto IEnumerable<T> dal quale restituire un elemento.

predicate
Func<TSource,Boolean>

Funzione per testare ogni elemento rispetto a una condizione.

Restituisce

TSource

default(TSource) se la sequenza è vuota o se nessun elemento supera il test nella funzione predicativa; in caso contrario, l'ultimo elemento che passa il test nella funzione predicativa.

Eccezioni

source o predicate è null.

Esempio

Nell'esempio di codice seguente viene illustrato come usare LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) passando un predicato. Nella seconda chiamata al metodo non è presente alcun elemento nella sequenza che soddisfa la condizione.

double[] numbers = { 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 };

double last50 = numbers.LastOrDefault(n => Math.Round(n) == 50.0);

Console.WriteLine("The last number that rounds to 50 is {0}.", last50);

double last40 = numbers.LastOrDefault(n => Math.Round(n) == 40.0);

Console.WriteLine(
    "The last number that rounds to 40 is {0}.",
    last40 == 0.0 ? "<DOES NOT EXIST>" : last40.ToString());

/*
 This code produces the following output:

 The last number that rounds to 50 is 50.2.
 The last number that rounds to 40 is <DOES NOT EXIST>.
*/
' Create an array of doubles.
Dim numbers() As Double = {49.6, 52.3, 51.0, 49.4, 50.2, 48.3}

' Get the last item whose value rounds to 50.0.
Dim number50 As Double =
numbers.LastOrDefault(Function(n) Math.Round(n) = 50.0)

Dim output As New System.Text.StringBuilder
output.AppendLine("The last number that rounds to 50 is " & number50)

' Get the last item whose value rounds to 40.0.
Dim number40 As Double =
numbers.LastOrDefault(Function(n) Math.Round(n) = 40.0)

Dim text As String = IIf(number40 = 0.0,
                     "[DOES NOT EXIST]",
                     number40.ToString())
output.AppendLine("The last number that rounds to 40 is " & text)

' Display the output.
Console.WriteLine(output.ToString)

' This code produces the following output:
'
' The last number that rounds to 50 is 50.2
' The last number that rounds to 40 is [DOES NOT EXIST]

Commenti

Il valore predefinito per i tipi di riferimento e nullable è null.

Si applica a

LastOrDefault<TSource>(IEnumerable<TSource>, TSource)

Restituisce l'ultimo elemento di una sequenza o un valore predefinito specificato se la sequenza non contiene elementi.

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

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IEnumerable<TSource>

Oggetto IEnumerable<T> di cui restituire l’ultimo elemento.

defaultValue
TSource

Valore predefinito da restituire se la sequenza è vuota.

Restituisce

TSource

defaultValue se la sequenza di origine è vuota; in caso contrario, l'ultimo elemento nell'oggetto IEnumerable<T>.

Eccezioni

source è null.

Si applica a

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

Restituisce l'ultimo elemento di una sequenza che soddisfa una condizione o un valore predefinito specificato se non viene trovato alcun elemento di questo tipo.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource LastOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate, TSource defaultValue);
public static TSource LastOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate, TSource defaultValue);
static member LastOrDefault : seq<'Source> * Func<'Source, bool> * 'Source -> 'Source
<Extension()>
Public Function LastOrDefault(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean), defaultValue As TSource) As TSource

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IEnumerable<TSource>

Oggetto IEnumerable<T> dal quale restituire un elemento.

predicate
Func<TSource,Boolean>

Funzione per testare ogni elemento rispetto a una condizione.

defaultValue
TSource

Valore predefinito da restituire se la sequenza è vuota.

Restituisce

TSource

defaultValue se la sequenza è vuota o se nessun elemento supera il test nella funzione predicato; in caso contrario, l'ultimo elemento che supera il test nella funzione predicato.

Eccezioni

source o predicate è null.

Si applica a