Queryable.SingleOrDefault 메서드

정의

시퀀스의 특정 단일 요소를 반환하거나, 이러한 요소가 없으면 기본값을 반환합니다.

오버로드

SingleOrDefault<TSource>(IQueryable<TSource>, TSource)

시퀀스의 유일한 요소를 반환하거나 시퀀스가 비어 있으면 기본값을 반환합니다. 시퀀스에 요소가 둘 이상 있으면 예외를 throw합니다.

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

시퀀스에서 지정된 조건에 맞는 유일한 요소를 반환하거나 이러한 요소가 없으면 기본값을 반환합니다. 조건에 맞는 요소가 둘 이상 있으면 예외를 throw합니다.

SingleOrDefault<TSource>(IQueryable<TSource>)

시퀀스의 유일한 요소를 반환하거나 시퀀스가 비어 있으면 기본값을 반환합니다. 시퀀스에 요소가 둘 이상 있으면 예외를 throw합니다.

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

시퀀스에서 지정된 조건에 맞는 유일한 요소를 반환하거나 이러한 요소가 없으면 기본값을 반환합니다. 조건에 맞는 요소가 둘 이상 있으면 예외를 throw합니다.

SingleOrDefault<TSource>(IQueryable<TSource>, TSource)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

시퀀스의 유일한 요소를 반환하거나 시퀀스가 비어 있으면 기본값을 반환합니다. 시퀀스에 요소가 둘 이상 있으면 예외를 throw합니다.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource SingleOrDefault(System::Linq::IQueryable<TSource> ^ source, TSource defaultValue);
public static TSource SingleOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, TSource defaultValue);
static member SingleOrDefault : System.Linq.IQueryable<'Source> * 'Source -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IQueryable(Of TSource), defaultValue As TSource) As TSource

형식 매개 변수

TSource

source 요소의 형식입니다.

매개 변수

source
IQueryable<TSource>

단일 요소를 반환할 IEnumerable<T>입니다.

defaultValue
TSource

시퀀스가 비어 있는 경우 반환할 기본값입니다.

반환

TSource

입력 시퀀스의 단일 요소이거나 defaultValue , 시퀀스에 요소가 없는 경우 입니다.

예외

source이(가) null인 경우

입력 시퀀스에 요소가 두 개 이상 있습니다.

적용 대상

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

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

시퀀스에서 지정된 조건에 맞는 유일한 요소를 반환하거나 이러한 요소가 없으면 기본값을 반환합니다. 조건에 맞는 요소가 둘 이상 있으면 예외를 throw합니다.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource SingleOrDefault(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate, TSource defaultValue);
public static TSource SingleOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate, TSource defaultValue);
static member SingleOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> * 'Source -> 'Source
<Extension()>
Public Function SingleOrDefault(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 또는 predicatenull인 경우

predicate의 조건에 맞는 요소가 둘 이상인 경우

적용 대상

SingleOrDefault<TSource>(IQueryable<TSource>)

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

시퀀스의 유일한 요소를 반환하거나 시퀀스가 비어 있으면 기본값을 반환합니다. 시퀀스에 요소가 둘 이상 있으면 예외를 throw합니다.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource SingleOrDefault(System::Linq::IQueryable<TSource> ^ source);
public static TSource SingleOrDefault<TSource> (this System.Linq.IQueryable<TSource> source);
public static TSource? SingleOrDefault<TSource> (this System.Linq.IQueryable<TSource> source);
static member SingleOrDefault : System.Linq.IQueryable<'Source> -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IQueryable(Of TSource)) As TSource

형식 매개 변수

TSource

source 요소의 형식입니다.

매개 변수

source
IQueryable<TSource>

단일 요소를 반환할 IQueryable<T>입니다.

반환

TSource

입력 시퀀스의 단일 요소이거나, 시퀀스에 요소가 없으면 default(TSource)입니다.

예외

source이(가) null인 경우

source에 둘 이상의 요소가 있는 경우

예제

다음 코드 예제에서는 를 사용하여 SingleOrDefault<TSource>(IQueryable<TSource>) 배열의 유일한 요소를 선택하는 방법을 보여 줍니다. 두 번째 쿼리는 시퀀스에 정확히 하나의 요소가 포함되지 않은 경우 기본값을 반환하는 SingleOrDefault<TSource>(IQueryable<TSource>) 것을 보여 줍니다.

// Create two arrays. The second is empty.
string[] fruits1 = { "orange" };
string[] fruits2 = { };

// Get the only item in the first array, or else
// the default value for type string (null).
string fruit1 = fruits1.AsQueryable().SingleOrDefault();
Console.WriteLine("First Query: " + fruit1);

// Get the only item in the second array, or else
// the default value for type string (null).
string fruit2 = fruits2.AsQueryable().SingleOrDefault();
Console.WriteLine("Second Query: " +
    (String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2));

/*
    This code produces the following output:

    First Query: orange
    Second Query: No such string!
*/
' Create two arrays. The second is empty.
Dim fruits1() As String = {"orange"}
Dim fruits2() As String = {}

' Get the only item in the first array, or else
' the default value for type string (null).
Dim fruit1 As String = fruits1.AsQueryable().SingleOrDefault()
MsgBox("First Query: " + fruit1)

' Get the only item in the second array, or else
' the default value for type string (null). 
Dim fruit2 As String = fruits2.AsQueryable().SingleOrDefault()
MsgBox("Second Query: " & _
    IIf(String.IsNullOrEmpty(fruit2), "No such string!", fruit2))

' This code produces the following output:

' First Query: orange
' Second Query: No such string!

컬렉션에 요소가 없는 경우 의 default(TSource) 값이 사용하려는 기본값이 아닌 경우가 있습니다. 원치 않는 기본값에 대한 결과를 확인한 다음 필요한 경우 변경하는 대신 메서드를 DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) 사용하여 컬렉션이 비어 있는 경우 사용할 기본값을 지정할 수 있습니다. 그런 다음 를 호출 Single<TSource>(IQueryable<TSource>) 하여 요소를 가져옵니다. 다음 코드 예제에서는 두 기술을 모두 사용하여 페이지 번호 컬렉션이 비어 있는 경우 기본값 1을 가져옵니다. 정수의 기본값은 일반적으로 유효한 페이지 번호가 아닌 0이므로 기본값은 대신 1로 지정해야 합니다. 첫 번째 결과 변수는 쿼리가 완료된 후 원치 않는 기본값을 확인합니다. 두 번째 결과 변수는 를 호출 DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) 하여 기본값 1을 지정하여 가져옵니다.

int[] pageNumbers = { };

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

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

/*
 This code produces the following output:

 The value of the pageNumber1 variable is 1
 The value of the pageNumber2 variable is 1
*/
Dim pageNumbers() As Integer = {}

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

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

' This code produces the following output:

' The value of the pageNumber1 variable is 1
' The value of the pageNumber2 variable is 1

설명

메서드는 SingleOrDefault<TSource>(IQueryable<TSource>)MethodCallExpression 생성된 제네릭 메서드로 자신을 호출 SingleOrDefault<TSource>(IQueryable<TSource>) 하는 를 나타내는 을 생성합니다. 그런 다음 을 MethodCallExpression 매개 변수의 Execute<TResult>(Expression) 속성으로 나타내는 의 IQueryProvider 메서드에 Providersource 전달합니다.

호출 SingleOrDefault<TSource>(IQueryable<TSource>) 을 나타내는 식 트리를 실행한 결과로 발생하는 쿼리 동작은 매개 변수 형식의 source 구현에 따라 달라집니다. 예상되는 동작은 의 source유일한 요소를 반환하거나 가 비어 있는 경우 기본값을 반환하는 것입니다 source .

메서드는 SingleOrDefault 기본값을 지정하는 방법을 제공하지 않습니다. 이외의 default(TSource)기본값을 지정하려면 예제 섹션에 DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) 설명된 대로 메서드를 사용합니다.

적용 대상

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

Source:
Queryable.cs
Source:
Queryable.cs
Source:
Queryable.cs

시퀀스에서 지정된 조건에 맞는 유일한 요소를 반환하거나 이러한 요소가 없으면 기본값을 반환합니다. 조건에 맞는 요소가 둘 이상 있으면 예외를 throw합니다.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource SingleOrDefault(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static TSource SingleOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
public static TSource? SingleOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member SingleOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
<Extension()>
Public Function SingleOrDefault(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

의 조건을 predicate충족하는 입력 시퀀스의 단일 요소이거나 default,TSource() 이러한 요소가 없는 경우 입니다.

예외

source 또는 predicatenull인 경우

predicate의 조건에 맞는 요소가 둘 이상인 경우

예제

다음 코드 예제에서는 를 사용하여 SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) 조건을 충족하는 배열의 유일한 요소를 선택하는 방법을 보여 줍니다. 두 번째 쿼리는 시퀀스에 조건을 충족하는 SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) 요소가 정확히 하나도 없을 때 기본값을 반환하는 것을 보여 줍니다.

string[] fruits = { "apple", "banana", "mango",
                      "orange", "passionfruit", "grape" };

// Get the single string in the array whose length is greater
// than 10, or else the default value for type string (null).
string fruit1 =
    fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 10);
Console.WriteLine("First Query: " + fruit1);

// Get the single string in the array whose length is greater
// than 15, or else the default value for type string (null).
string fruit2 =
   fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 15);
Console.WriteLine("Second Query: " +
    (String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2));

/*
    This code produces the following output:

    First Query: passionfruit
    Second Query: No such string!
*/
Dim fruits() As String = _
    {"apple", "banana", "mango", "orange", "passionfruit", "grape"}

' Get the single string in the array whose length is greater
' than 10, or else the default value for type string (null).
Dim fruit1 As String = _
    fruits.AsQueryable().SingleOrDefault(Function(fruit) fruit.Length > 10)
' Display the result.
MsgBox("First Query: " & fruit1)

' Get the single string in the array whose length is greater
' than 15, or else the default value for type string (null).
Dim fruit2 As String = _
    fruits.AsQueryable().SingleOrDefault(Function(fruit) fruit.Length > 15)
MsgBox("Second Query: " & _
    IIf(String.IsNullOrEmpty(fruit2), "No such string!", fruit2))

' This code produces the following output:

' First Query: passionfruit
' Second Query: No such string!

설명

이 메서드에는 형식 인수가 형식 중 하나인 형식 Expression<TDelegate> 의 매개 변수가 Func<T,TResult> 하나 이상 있습니다. 이러한 매개 변수의 경우 람다 식을 전달할 수 있으며 에 컴파일됩니다 Expression<TDelegate>.

메서드는 SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)MethodCallExpression 생성된 제네릭 메서드로 자신을 호출 SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) 하는 를 나타내는 을 생성합니다. 그런 다음 을 MethodCallExpression 매개 변수의 Execute<TResult>(Expression) 속성으로 나타내는 의 IQueryProvider 메서드에 Providersource 전달합니다.

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

적용 대상