Queryable.FirstOrDefault メソッド

定義

シーケンスの最初の要素を返します。要素が見つからない場合は既定値を返します。

オーバーロード

名前 説明
FirstOrDefault<TSource>(IQueryable<TSource>)

シーケンスの最初の要素を返します。シーケンスに要素が含まれている場合は既定値を返します。

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

指定した条件を満たすシーケンスの最初の要素、またはそのような要素が見つからない場合は既定値を返します。

FirstOrDefault<TSource>(IQueryable<TSource>)

シーケンスの最初の要素を返します。シーケンスに要素が含まれている場合は既定値を返します。

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);
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

default sourceが空の場合は (TSource)、それ以外の場合はsourceの最初の要素。

例外

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 として指定する必要があります。 クエリが完了した後、最初の結果変数に不要な既定値がチェックされます。 2 番目の結果変数は、既定値の 1 を指定するために DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) を呼び出すことによって取得されます。

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>)を生成します。 次に、MethodCallExpression パラメーターのExecute<TResult>(Expression) プロパティで表されるIQueryProviderProvider メソッドに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>>)

指定した条件を満たすシーケンスの最初の要素、またはそのような要素が見つからない場合は既定値を返します。

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);
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で指定されたテストに合格する要素がない場合は。それ以外の場合は、predicateで指定されたテストに合格するsourceの最初の要素。

例外

source または predicatenull

次のコード例では、述語を渡して FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) を使用する方法を示します。 2 番目のクエリでは、条件を満たす要素がシーケンス内にありません。

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>型の 1 つである型Func<T,TResult>のパラメーターが少なくとも 1 つ含まれています。 これらのパラメーターでは、ラムダ式を渡すことができます。ラムダ式は Expression<TDelegate>にコンパイルされます。

FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) メソッドは、構築されたジェネリック メソッドとしての呼び出しMethodCallExpression自体を表すFirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)を生成します。 次に、MethodCallExpression パラメーターのExecute<TResult>(Expression) プロパティで表されるIQueryProviderProvider メソッドにsourceを渡します。

呼び出し FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) を表す式ツリーを実行した結果として発生するクエリ動作は、 source パラメーターの型の実装によって異なります。 予期される動作は、predicateの条件を満たすsourceの最初の要素を返すか、条件を満たす要素がない場合は既定値を返します。

適用対象