Enumerable.LastOrDefault Метод

Определение

Возвращает последний элемент последовательности или значение по умолчанию, если элемент не найден.

Перегрузки

Имя Описание
LastOrDefault<TSource>(IEnumerable<TSource>)

Возвращает последний элемент последовательности или значение по умолчанию, если последовательность не содержит элементов.

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

Возвращает последний элемент последовательности, удовлетворяющей условию или значению по умолчанию, если такой элемент не найден.

LastOrDefault<TSource>(IEnumerable<TSource>)

Возвращает последний элемент последовательности или значение по умолчанию, если последовательность не содержит элементов.

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

Параметры типа

TSource

Тип элементов source.

Параметры

source
IEnumerable<TSource>

Значение, IEnumerable<T> возвращаемое последним элементом.

Возвращаемое значение

TSource

default(TSource) Значение , если исходная последовательность пуста; в противном случае — последний элемент в элементе IEnumerable<T>.

Исключения

source равно null.

Примеры

В следующем примере кода показано, как использовать LastOrDefault<TSource>(IEnumerable<TSource>) в пустом массиве.

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>

Иногда значение не является значением default(TSource) по умолчанию, которое требуется использовать, если коллекция не содержит элементов. Вместо проверки результата для нежелательного значения по умолчанию и изменения его при необходимости можно использовать DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) метод, чтобы указать значение по умолчанию, которое необходимо использовать, если коллекция пуста. Затем вызовите Last<TSource>(IEnumerable<TSource>) , чтобы получить последний элемент. В следующем примере кода используются оба метода для получения значения по умолчанию 1, если коллекция числовых дней месяца пуста. Так как значение по умолчанию для целого числа равно 0, которое не соответствует ни одному дню месяца, значение по умолчанию должно быть указано как 1. Первая переменная результата проверяется на нежелательное значение по умолчанию после завершения выполнения запроса. Вторая переменная результата получается с помощью DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) указания значения по умолчанию 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

Комментарии

Значением по умолчанию для ссылочных и типы, допускающие значение NULL, является null.

Метод LastOrDefault не предоставляет способ указания значения по умолчанию. Если вы хотите указать значение по умолчанию, отличное default(TSource)от этого, используйте DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) метод, как описано в разделе "Пример".

Применяется к

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

Возвращает последний элемент последовательности, удовлетворяющей условию или значению по умолчанию, если такой элемент не найден.

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

Параметры типа

TSource

Тип элементов source.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T> , из который возвращается элемент.

predicate
Func<TSource,Boolean>

Функция для проверки каждого элемента для условия.

Возвращаемое значение

TSource

default(TSource) Значение , если последовательность пуста или если элементы не передают тест в функции предиката; в противном случае последний элемент, который передает тест в функции предиката.

Исключения

source или predicate есть null.

Примеры

В следующем примере кода показано, как использовать LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) путем передачи предиката. Во втором вызове метода элемент в последовательности, удовлетворяющей условию, отсутствует.

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]

Комментарии

Значением по умолчанию для ссылочных и типы, допускающие значение NULL, является null.

Применяется к