Queryable.LastOrDefault Metodo

Definizione

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

Overload

LastOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>, TSource)

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

LastOrDefault<TSource>(IQueryable<TSource>, TSource)

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

LastOrDefault<TSource>(IQueryable<TSource>, Expression<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>(IQueryable<TSource>)

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

LastOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>, TSource)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

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::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate, TSource defaultValue);
public static TSource LastOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate, TSource defaultValue);
static member LastOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> * 'Source -> 'Source
<Extension()>
Public Function LastOrDefault(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean)), defaultValue As TSource) As TSource

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IQueryable<TSource>

Oggetto IEnumerable<T> dal quale restituire un elemento.

predicate
Expression<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

LastOrDefault<TSource>(IQueryable<TSource>, TSource)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

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::Linq::IQueryable<TSource> ^ source, TSource defaultValue);
public static TSource LastOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, TSource defaultValue);
static member LastOrDefault : System.Linq.IQueryable<'Source> * 'Source -> 'Source
<Extension()>
Public Function LastOrDefault(Of TSource) (source As IQueryable(Of TSource), defaultValue As TSource) As TSource

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IQueryable<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>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

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::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static TSource LastOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
public static TSource? LastOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member LastOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
<Extension()>
Public Function LastOrDefault(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As TSource

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IQueryable<TSource>

Oggetto IQueryable<T> dal quale restituire un elemento.

predicate
Expression<Func<TSource,Boolean>>

Funzione per testare ogni elemento rispetto a una condizione.

Restituisce

TSource

default(TSource) se source è vuoto o se nessun elemento supera il test nella funzione predicato; in caso contrario, l'ultimo elemento di source che supera il test nella funzione predicato.

Eccezioni

source o predicate è null.

Esempio

Nell'esempio di codice seguente viene illustrato come usare LastOrDefault<TSource>(IQueryable<TSource>, Expression<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 };

// Get the last number in the array that rounds to 50.0,
// or else the default value for type double (0.0).
double last50 =
    numbers.AsQueryable().LastOrDefault(n => Math.Round(n) == 50.0);

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

// Get the last number in the array that rounds to 40.0,
// or else the default value for type double (0.0).
double last40 =
    numbers.AsQueryable().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].
*/
Dim numbers() As Double = {49.6, 52.3, 51.0, 49.4, 50.2, 48.3}

' Get the last number in the array that rounds to 50.0,
' or else the default value for type double (0.0).
Dim last50 As Double = _
     numbers.AsQueryable().LastOrDefault(Function(n) Math.Round(n) = 50.0)

MsgBox(String.Format("The last number that rounds to 50 is {0}.", last50))

' Get the last number in the array that rounds to 40.0,
' or else the default value for type double (0.0).
Dim last40 As Double = _
    numbers.AsQueryable().LastOrDefault(Function(n) Math.Round(n) = 40.0)

MsgBox(String.Format("The last number that rounds to 40 is {0}.", _
    IIf(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].

Commenti

Questo metodo ha almeno un parametro di tipo Expression<TDelegate> il cui argomento di tipo è uno dei Func<T,TResult> tipi . Per questi parametri, è possibile passare un'espressione lambda e verrà compilata in un oggetto Expression<TDelegate>.

Il LastOrDefault<TSource>(IQueryable<TSource>) metodo genera un MethodCallExpression oggetto che rappresenta LastOrDefault<TSource>(IQueryable<TSource>) se stesso come metodo generico costruito. Passa quindi l'oggetto MethodCallExpression al Execute<TResult>(Expression) metodo dell'oggetto IQueryProvider rappresentato dalla Provider proprietà del source parametro .

Il comportamento della query che si verifica come risultato dell'esecuzione di un albero delle espressioni che rappresenta la chiamata LastOrDefault<TSource>(IQueryable<TSource>) dipende dall'implementazione del tipo del source parametro. Il comportamento previsto è che restituisce l'ultimo elemento in source che soddisfa la condizione specificata da predicate. Restituisce un valore predefinito se non esiste un elemento di questo tipo in source.

Si applica a

LastOrDefault<TSource>(IQueryable<TSource>)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

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

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

Parametri di tipo

TSource

Tipo degli elementi di source.

Parametri

source
IQueryable<TSource>

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

Restituisce

TSource

default(TSource) se source è vuoto; in caso contrario, l'ultimo elemento in source.

Eccezioni

source è null.

Esempio

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

// Create an empty array.
string[] fruits = { };

// Get the last item in the array, or else the default
// value for type string (null).
string last = fruits.AsQueryable().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 else the default
' value for type string (null).
Dim last As String = fruits.AsQueryable().LastOrDefault()

MsgBox(IIf(String.IsNullOrEmpty(last), "[STRING IS NULL OR EMPTY]", last))

' This code produces the following output:
' [STRING IS NULL 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 usare il metodo per specificare il DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) valore predefinito che si desidera utilizzare se la raccolta è vuota. Chiamare Last<TSource>(IQueryable<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 verificata per il valore predefinito indesiderato dopo il completamento della query. La seconda variabile di risultato viene ottenuta chiamando DefaultIfEmpty<TSource>(IQueryable<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.AsQueryable().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.AsQueryable().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.AsQueryable().LastOrDefault()
If lastDay1 = 0 Then
    lastDay1 = 1
End If
MsgBox(String.Format("The value of the lastDay1 variable is {0}", lastDay1))

' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim lastDay2 As Integer = daysOfMonth.AsQueryable().DefaultIfEmpty(1).Last()
MsgBox(String.Format("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

Commenti

Il LastOrDefault<TSource>(IQueryable<TSource>) metodo genera un MethodCallExpression oggetto che rappresenta LastOrDefault<TSource>(IQueryable<TSource>) se stesso come metodo generico costruito. Passa quindi l'oggetto MethodCallExpression al Execute<TResult>(Expression) metodo dell'oggetto IQueryProvider rappresentato dalla Provider proprietà del source parametro .

Il comportamento della query che si verifica come risultato dell'esecuzione di un albero delle espressioni che rappresenta la chiamata LastOrDefault<TSource>(IQueryable<TSource>) dipende dall'implementazione del tipo del source parametro. Il comportamento previsto è che restituisce l'ultimo elemento in sourceo un valore predefinito se source è vuoto.

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>(IQueryable<TSource>, TSource) metodo come descritto nella sezione Esempio.

Si applica a