Queryable.FirstOrDefault 메서드

정의

시퀀스의 첫 번째 요소를 반환하거나, 요소가 없으면 기본값을 반환합니다.

오버로드

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

시퀀스에서 특정 조건에 맞는 첫 번째 요소를 반환하거나, 이러한 요소가 없으면 기본값을 반환합니다.

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)

시퀀스에서 특정 조건에 맞는 첫 번째 요소를 반환하거나, 이러한 요소가 없으면 기본값을 반환합니다.

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

defaultValuesource 비어 있거나 지정된 테스트를 predicate통과하는 요소가 없으면 이고, 그렇지 않으면 지정된 테스트를 predicate통과하는 첫 번째 요소 source 입니다.

예외

source 또는 predicatenull인 경우

적용 대상

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

시퀀스의 첫 번째 요소를 반환하거나, 시퀀스에 요소가 없으면 기본값을 반환합니다.

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);
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 if source is empty; otherwise, the first element in source.

예외

source이(가) null인 경우

적용 대상

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

source가 비어 있으면 default(TSource)이고, 그렇지 않으면 source의 첫 번째 요소입니다.

예외

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로 지정해야 합니다. 첫 번째 결과 변수는 쿼리가 완료된 후 원치 않는 기본값을 확인합니다. 두 번째 결과 변수는 기본값 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>) 생성된 제네릭 메서드로 자신을 호출 FirstOrDefault<TSource>(IQueryable<TSource>) 하는 것을 나타내는 값을 생성 MethodCallExpression 합니다. 그런 다음 매개 변수의 IQueryProvider 속성이 나타내는 메서드에 Provider source 전달 MethodCallExpression Execute<TResult>(Expression) 합니다.

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

source가 비어 있거나 predicate에 지정된 테스트를 통과하는 요소가 없으면 default(TSource)이고, 그렇지 않으면 source에서 predicate에 지정된 테스트를 통과하는 첫 번째 요소입니다.

예외

source 또는 predicatenull인 경우

예제

다음 코드 예제에서는 조건자를 전달하여 사용하는 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>>) 생성된 제네릭 메서드로 자신을 호출 FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) 하는 것을 나타내는 값을 생성 MethodCallExpression 합니다. 그런 다음 매개 변수의 IQueryProvider 속성이 나타내는 메서드에 Provider source 전달 MethodCallExpression Execute<TResult>(Expression) 합니다.

호출 FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) 을 나타내는 식 트리를 실행한 결과로 발생하는 쿼리 동작은 매개 변수 형식 source 의 구현에 따라 달라집니다. 예상되는 동작은 조건을 충족하는 첫 번째 요소를 반환하거나 조건을 predicate충족하는 요소가 source 없는 경우 기본값을 반환하는 것입니다.

적용 대상