Enumerable.LastOrDefault Método

Definição

Retornará o último elemento de uma sequência ou um valor padrão se nenhum elemento for encontrado.

Sobrecargas

LastOrDefault<TSource>(IEnumerable<TSource>)

Retorna o último elemento de uma sequência ou um valor padrão se a sequência não contém elementos.

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

Retorna o último elemento de uma sequência que satisfaz uma condição ou um valor padrão, caso esse elemento não seja encontrado.

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

Retorna o último elemento de uma sequência ou um valor padrão especificado se a sequência não contiver elementos.

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

Retorna o último elemento de uma sequência que atende a uma condição ou um valor padrão especificado se nenhum elemento desse tipo for encontrado.

LastOrDefault<TSource>(IEnumerable<TSource>)

Origem:
Last.cs
Origem:
Last.cs
Origem:
Last.cs

Retorna o último elemento de uma sequência ou um valor padrão se a sequência não contém elementos.

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

Parâmetros de tipo

TSource

O tipo dos elementos de source.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> do qual o último elemento será retornado.

Retornos

TSource

default(TSource) se a sequência de origem estiver vazia; caso contrário, o último elemento no IEnumerable<T>.

Exceções

source é null.

Exemplos

O exemplo de código a seguir demonstra como usar LastOrDefault<TSource>(IEnumerable<TSource>) em uma matriz vazia.

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>

Às vezes, o valor de default(TSource) não é o valor padrão que você deseja usar se a coleção não contiver elementos. Em vez de verificar o resultado do valor padrão indesejado e alterá-lo, se necessário, você pode usar o DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) método para especificar o valor padrão que deseja usar se a coleção estiver vazia. Em seguida, chame Last<TSource>(IEnumerable<TSource>) para obter o último elemento. O exemplo de código a seguir usa ambas as técnicas para obter um valor padrão de 1 se uma coleção de dias numéricos do mês estiver vazia. Como o valor padrão de um inteiro é 0, que não corresponde a nenhum dia do mês, o valor padrão deve ser especificado como 1. A primeira variável de resultado é verificada quanto ao valor padrão indesejado após a execução da consulta. A segunda variável de resultado é obtida usando DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) para especificar um valor padrão de 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

Comentários

O valor padrão para tipos de referência e anuláveis é null.

O LastOrDefault método não fornece uma maneira de especificar um valor padrão. Se você quiser especificar um valor padrão diferente de default(TSource), use o DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) método conforme descrito na seção Exemplo.

Aplica-se a

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

Origem:
Last.cs
Origem:
Last.cs
Origem:
Last.cs

Retorna o último elemento de uma sequência que satisfaz uma condição ou um valor padrão, caso esse elemento não seja encontrado.

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

Parâmetros de tipo

TSource

O tipo dos elementos de source.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> do qual um elemento será retornado.

predicate
Func<TSource,Boolean>

Uma função para testar cada elemento em relação a uma condição.

Retornos

TSource

default(TSource) se a sequência for vazia ou se nenhum elemento passar no teste na função de predicado; caso contrário, o último elemento que passar no teste na função de predicado.

Exceções

source ou predicate é null.

Exemplos

O exemplo de código a seguir demonstra como usar LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) passando um predicado. Na segunda chamada para o método , não há nenhum elemento na sequência que satisfaça a condição.

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]

Comentários

O valor padrão para tipos de referência e anuláveis é null.

Aplica-se a

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

Origem:
Last.cs
Origem:
Last.cs
Origem:
Last.cs

Retorna o último elemento de uma sequência ou um valor padrão especificado se a sequência não contiver elementos.

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

Parâmetros de tipo

TSource

O tipo dos elementos de source.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> do qual o último elemento será retornado.

defaultValue
TSource

O valor padrão a ser retornado se a sequência estiver vazia.

Retornos

TSource

defaultValue se a sequência de origem estiver vazia; caso contrário, o último elemento no IEnumerable<T>.

Exceções

source é null.

Aplica-se a

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

Origem:
Last.cs
Origem:
Last.cs
Origem:
Last.cs

Retorna o último elemento de uma sequência que atende a uma condição ou um valor padrão especificado se nenhum elemento desse tipo for encontrado.

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

Parâmetros de tipo

TSource

O tipo dos elementos de source.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> do qual um elemento será retornado.

predicate
Func<TSource,Boolean>

Uma função para testar cada elemento em relação a uma condição.

defaultValue
TSource

O valor padrão a ser retornado se a sequência estiver vazia.

Retornos

TSource

defaultValue se a sequência estiver vazia ou se nenhum elemento passar no teste na função de predicado; caso contrário, o último elemento que passa no teste na função de predicado.

Exceções

source ou predicate é null.

Aplica-se a