Enumerable.LastOrDefault Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Restituisce l'ultimo elemento di una sequenza o un valore predefinito se non viene trovato alcun elemento.
Overload
| Nome | Descrizione |
|---|---|
| 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 o un valore predefinito 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);
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.
Valori restituiti
default(TSource) se la sequenza di origine è vuota; in caso contrario, l'ultimo elemento dell'oggetto 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 desidera utilizzare se la raccolta non contiene elementi. Anziché controllare il risultato per il valore predefinito indesiderato e modificarlo, se necessario, è possibile utilizzare il DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) metodo per specificare il valore predefinito che si desidera utilizzare se la raccolta è vuota. Chiamare Last<TSource>(IEnumerable<TSource>) quindi per ottenere l'ultimo elemento. Nell'esempio di codice seguente vengono utilizzate 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 numero intero è 0, che non corrisponde ad alcun giorno del mese, il valore predefinito deve essere specificato come 1. La prima variabile di risultato viene controllata per il valore predefinito indesiderato al termine 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 reference e nullable è null.
Il LastOrDefault metodo non fornisce un modo per specificare un valore predefinito. Se si desidera 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 o un valore predefinito 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);
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> da cui restituire un elemento.
Valori restituiti
default(TSource) 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.
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 esiste 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 reference e nullable è null.