Enumerable.SingleOrDefault 메서드

정의

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

오버로드

SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)

시퀀스의 유일한 요소를 반환하거나 시퀀스가 비어 있는 경우 지정된 기본값을 반환합니다. 시퀀스에 요소가 두 개 이상 있는 경우 이 메서드는 예외를 throw합니다.

SingleOrDefault<TSource>(IEnumerable<TSource>)

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

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

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

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

지정된 조건을 충족하는 시퀀스의 유일한 요소 또는 이러한 요소가 없는 경우 지정된 기본값을 반환합니다. 이 메서드는 둘 이상의 요소가 조건을 충족하는 경우 예외를 throw합니다.

SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)

시퀀스의 유일한 요소를 반환하거나 시퀀스가 비어 있는 경우 지정된 기본값을 반환합니다. 시퀀스에 요소가 두 개 이상 있는 경우 이 메서드는 예외를 throw합니다.

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

형식 매개 변수

TSource

source 요소의 형식입니다.

매개 변수

source
IEnumerable<TSource>

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

defaultValue
TSource

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

반환

TSource

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

예외

source이(가) null인 경우

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

적용 대상

SingleOrDefault<TSource>(IEnumerable<TSource>)

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

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

형식 매개 변수

TSource

source 요소의 형식입니다.

매개 변수

source
IEnumerable<TSource>

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

반환

TSource

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

예외

source이(가) null인 경우

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

예제

다음 코드 예제에서는 배열의 유일한 요소를 선택 하는 데 사용 SingleOrDefault<TSource>(IEnumerable<TSource>) 하는 방법을 보여 줍니다.

string[] fruits1 = { "orange" };

string fruit1 = fruits1.SingleOrDefault();

Console.WriteLine(fruit1);

/*
 This code produces the following output:

 orange
*/
' Create an array that contains one item.
Dim fruits1() As String = {"orange"}

' Get the single item in the array or else a default value.
Dim result As String = fruits1.SingleOrDefault()

' Display the result.
Console.WriteLine($"First array: {result}")

다음 코드 예제에서는 시퀀스가 비어 있을 때 기본값을 반환하는 방법을 SingleOrDefault<TSource>(IEnumerable<TSource>) 보여 줍니다.

string[] fruits2 = { };

string fruit2 = fruits2.SingleOrDefault();

Console.WriteLine(
    String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);

/*
 This code produces the following output:

 No such string!
*/
' Create an empty array.
Dim fruits2() As String = {}

result = String.Empty

' Get the single item in the array or else a default value.
result = fruits2.SingleOrDefault()

' Display the result.
Dim output As String =
IIf(String.IsNullOrEmpty(result), "No single item found", result)
Console.WriteLine($"Second array: {output}")

' This code produces the following output:
'
' First array: orange
' Second array: No single item found

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

int[] pageNumbers = { };

// Setting the default value to 1 after the query.
int pageNumber1 = pageNumbers.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.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.SingleOrDefault()
If pageNumber1 = 0 Then
    pageNumber1 = 1
End If
Console.WriteLine($"The value of the pageNumber1 variable is {pageNumber1}")

' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim pageNumber2 As Integer = pageNumbers.DefaultIfEmpty(1).Single()
Console.WriteLine($"The value of the pageNumber2 variable is {pageNumber2}")

' This code produces the following output:

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

설명

참조 및 nullable 형식의 기본값은 .입니다 null.

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

적용 대상

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

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

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource SingleOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate);
public static TSource SingleOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
public static TSource? SingleOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
static member SingleOrDefault : seq<'Source> * Func<'Source, bool> -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean)) As TSource

형식 매개 변수

TSource

source 요소의 형식입니다.

매개 변수

source
IEnumerable<TSource>

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

predicate
Func<TSource,Boolean>

요소를 조건에 대해 테스트하는 함수입니다.

반환

TSource

입력 시퀀스에서 조건에 맞는 단일 요소이거나, 이러한 요소가 없으면 default(TSource)입니다.

예외

source 또는 predicatenull인 경우

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

예제

다음 코드 예제에서는 조건을 충족 하는 배열의 유일한 요소를 선택 하는 방법을 보여 SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 줍니다.

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

string fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10);

Console.WriteLine(fruit1);

/*
 This code produces the following output:

 passionfruit
*/
' Create an array of strings.
Dim fruits() As String =
{"apple", "banana", "mango", "orange", "passionfruit", "grape"}

' Get the single item in the array whose length is > 10.
Dim fruit1 As String =
fruits.SingleOrDefault(Function(fruit) fruit.Length > 10)

' Display the result.
Console.WriteLine($"First array: {fruit1}")

다음 코드 예제에서는 시퀀스에 조건을 충족하는 SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 요소가 없는 경우 기본값을 반환하는 방법을 보여 줍니다.

string fruit2 =
    fruits.SingleOrDefault(fruit => fruit.Length > 15);

Console.WriteLine(
    String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);

/*
 This code produces the following output:

 No such string!
*/
' Get the single item in the array whose length is > 15.
Dim fruit2 As String =
fruits.SingleOrDefault(Function(fruit) fruit.Length > 15)

' Display the result.
Dim output As String =
IIf(String.IsNullOrEmpty(fruit2), "No single item found", fruit2)
Console.WriteLine($"Second array: {output}")

' This code produces the following output:
'
' First array: passionfruit
' Second array: No single item found

설명

참조 및 nullable 형식의 기본값은 .입니다 null.

적용 대상

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

지정된 조건을 충족하는 시퀀스의 유일한 요소 또는 이러한 요소가 없는 경우 지정된 기본값을 반환합니다. 이 메서드는 둘 이상의 요소가 조건을 충족하는 경우 예외를 throw합니다.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource SingleOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate, TSource defaultValue);
public static TSource SingleOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate, TSource defaultValue);
static member SingleOrDefault : seq<'Source> * Func<'Source, bool> * 'Source -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean), defaultValue As TSource) As TSource

형식 매개 변수

TSource

source 요소의 형식입니다.

매개 변수

source
IEnumerable<TSource>

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

predicate
Func<TSource,Boolean>

요소를 조건에 대해 테스트하는 함수입니다.

defaultValue
TSource

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

반환

TSource

조건을 충족하는 입력 시퀀스의 단일 요소이거나 defaultValue 이러한 요소가 없는 경우

예외

source 또는 predicatenull인 경우

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

적용 대상