Queryable.FirstOrDefault Метод

Определение

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

Перегрузки

Имя Описание
FirstOrDefault<TSource>(IQueryable<TSource>, TSource)

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

FirstOrDefault<TSource>(IQueryable<TSource>)

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

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

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

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

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

FirstOrDefault<TSource>(IQueryable<TSource>, TSource)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source, TSource defaultValue);
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, TSource defaultValue);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, TSource defaultValue);
static member FirstOrDefault : System.Linq.IQueryable<'Source> * 'Source -> 'Source
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member FirstOrDefault : System.Linq.IQueryable<'Source> * 'Source -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource), defaultValue As TSource) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

Возвращает IEnumerable<T> первый элемент.

defaultValue
TSource

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

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

TSource

defaultValue Значение , если source значение пусто; в противном случае — первый элемент source.

Атрибуты

Исключения

source равно null.

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

FirstOrDefault<TSource>(IQueryable<TSource>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source);
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source);
public static TSource? FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TSource? FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source);
static member FirstOrDefault : System.Linq.IQueryable<'Source> -> 'Source
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member FirstOrDefault : System.Linq.IQueryable<'Source> -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource)) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

Возвращает IQueryable<T> первый элемент.

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

TSource

() Значение >, если значение пусто; в противном случае — первый элемент в .

Атрибуты

Исключения

source равно null.

Примеры

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

// Create an empty array.
int[] numbers = { };
// Get the first item in the array, or else the
// default value for type int (0).
int first = numbers.AsQueryable().FirstOrDefault();

Console.WriteLine(first);

/*
    This code produces the following output:

    0
*/
' Create an empty array.
Dim numbers() As Integer = {}
' Get the first item in the array, or else the 
' default value for type int, which is 0.
Dim first As Integer = numbers.AsQueryable().FirstOrDefault()

MsgBox(first)

' This code produces the following output:

' 0

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

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

// Setting the default value to 1 after the query.
int firstMonth1 = months.AsQueryable().FirstOrDefault();
if (firstMonth1 == 0)
{
    firstMonth1 = 1;
}
Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1);

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

/*
 This code produces the following output:

 The value of the firstMonth1 variable is 1
 The value of the firstMonth2 variable is 1
*/
Dim months As New List(Of Integer)(New Integer() {})

' Setting the default value to 1 after the query.
Dim firstMonth1 As Integer = months.AsQueryable().FirstOrDefault()
If firstMonth1 = 0 Then
    firstMonth1 = 1
End If
MsgBox(String.Format("The value of the firstMonth1 variable is {0}", firstMonth1))

' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim firstMonth2 As Integer = months.AsQueryable().DefaultIfEmpty(1).First()
MsgBox(String.Format("The value of the firstMonth2 variable is {0}", firstMonth2))

' This code produces the following output:
'
' The value of the firstMonth1 variable is 1
' The value of the firstMonth2 variable is 1

Комментарии

Метод FirstOrDefault<TSource>(IQueryable<TSource>) создает объект MethodCallExpression , представляющий FirstOrDefault<TSource>(IQueryable<TSource>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов FirstOrDefault<TSource>(IQueryable<TSource>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает первый элемент в source, или значение по умолчанию, если source пусто.

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

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

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

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
public static TSource? FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TSource? FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member FirstOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member FirstOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

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

predicate
Expression<Func<TSource,Boolean>>

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

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

TSource

default(TSource) значение , если source элемент пуст или не передает тест, указанный predicateв ; в противном случае первый элемент, source который передает тест, указанный в параметре predicate.

Атрибуты

Исключения

source или predicate есть null.

Примеры

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

string[] names = { "Hartono, Tommy", "Adams, Terry",
                     "Andersen, Henriette Thaulow",
                     "Hedlund, Magnus", "Ito, Shu" };

// Get the first string in the array that is longer
// than 20 characters, or the default value for type
// string (null) if none exists.
string firstLongName =
    names.AsQueryable().FirstOrDefault(name => name.Length > 20);

Console.WriteLine("The first long name is '{0}'.", firstLongName);

// Get the first string in the array that is longer
// than 30 characters, or the default value for type
// string (null) if none exists.
string firstVeryLongName =
    names.AsQueryable().FirstOrDefault(name => name.Length > 30);

Console.WriteLine(
    "There is {0} name that is longer than 30 characters.",
    string.IsNullOrEmpty(firstVeryLongName) ? "NOT a" : "a");

/*
    This code produces the following output:

    The first long name is 'Andersen, Henriette Thaulow'.
    There is NOT a name that is longer than 30 characters.
*/
Dim names() As String = {"Hartono, Tommy", "Adams, Terry", _
                     "Andersen, Henriette Thaulow", _
                     "Hedlund, Magnus", "Ito, Shu"}

' Get the first string in the array that is longer
' than 20 characters, or the default value for type
' string (null) if none exists.
Dim firstLongName As String = _
            names.AsQueryable().FirstOrDefault(Function(name) name.Length > 20)

MsgBox(String.Format("The first long name is '{0}'.", firstLongName))

' Get the first string in the array that is longer
' than 30 characters, or the default value for type
' string (null) if none exists.
Dim firstVeryLongName As String = _
    names.AsQueryable().FirstOrDefault(Function(name) name.Length > 30)

MsgBox(String.Format( _
    "There is {0} name that is longer than 30 characters.", _
    IIf(String.IsNullOrEmpty(firstVeryLongName), "NOT a", "a")))

' This code produces the following output:
'
' The first long name is 'Andersen, Henriette Thaulow'.
' There is NOT a name that is longer than 30 characters.

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) создает объект MethodCallExpression , представляющий FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает первый элемент, удовлетворяющий source условию predicate, или значение по умолчанию, если элемент не удовлетворяет условию.

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

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

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate, TSource defaultValue);
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate, TSource defaultValue);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate, TSource defaultValue);
static member FirstOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> * 'Source -> 'Source
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member FirstOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> * 'Source -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean)), defaultValue As TSource) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

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

predicate
Expression<Func<TSource,Boolean>>

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

defaultValue
TSource

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

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

TSource

defaultValue Значение , если source элемент не проходит тест, predicateуказанный ; в противном случае первый элемент в source этом случае передает тест, указанный в predicateпараметре.

Атрибуты

Исключения

source или predicate есть null.

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