Queryable.FirstOrDefault 方法

定义

返回序列的第一个元素;如果未找到任何元素,则返回默认值。

重载

名称 说明
FirstOrDefault<TSource>(IQueryable<TSource>)

返回序列的第一个元素;如果序列不包含任何元素,则返回默认值。

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

返回满足指定条件的序列的第一个元素;如果未找到此类元素,则返回默认值。

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

返回序列的第一个元素;如果序列不包含任何元素,则返回默认值。

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

返回满足条件的序列的第一个元素;如果未找到此类元素,则返回默认值。

FirstOrDefault<TSource>(IQueryable<TSource>)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
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

() 如果为空,则为 />;否则为第一个元素。

属性

例外

sourcenull

示例

下面的代码示例演示如何对空序列使用 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>>)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
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

defaultTSource) 如果 source 为空,或者没有元素通过指定的 predicate测试,则为空;否则,该元素中的 source 第一个元素通过指定的 predicate测试。

属性

例外

sourcepredicatenull.

示例

下面的代码示例演示如何通过传入谓词来使用 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> 一。 对于这些参数,可以传入 lambda 表达式,并将它编译为一个 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 实现。 预期行为是,它返回满足条件中的sourcepredicate第一个元素;如果没有元素满足条件,则返回默认值。

适用于

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

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
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

属性

例外

sourcenull

适用于

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

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs
Source:
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测试。

属性

例外

sourcepredicatenull.

适用于