Enumerable.SingleOrDefault Enumerable.SingleOrDefault Enumerable.SingleOrDefault Enumerable.SingleOrDefault Method

定義

傳回序列或預設值的單一特定項目,如果找不到該項目。Returns a single, specific element of a sequence, or a default value if that element is not found.

多載

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

如果序列是空的則會傳回序列,則為預設值的唯一項目如果序列中有多個項目,則這個方法會擲回例外狀況。Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

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

傳回序列中符合指定之條件的唯一一個元素,如果沒有這類元素,則為預設值,如果有一個以上的元素符合條件,這個方法就會擲回例外狀況。Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.

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

如果序列是空的則會傳回序列,則為預設值的唯一項目如果序列中有多個項目,則這個方法會擲回例外狀況。Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

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);
static member SingleOrDefault : seq<'Source> -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IEnumerable(Of TSource)) As TSource

類型參數

TSource

source 項目的類型。The type of the elements of source.

參數

source
IEnumerable<TSource>

IEnumerable<T>来傳回的單一項目。An IEnumerable<T> to return the single element of.

傳回

TSource TSource TSource TSource

輸入序列的單一項目或default(TSource) 如果序列不包含任何項目。The single element of the input sequence, or default(TSource) if the sequence contains no elements.

例外狀況

輸入的序列包含一個以上的項目。The input sequence contains more than one element.

範例

下列程式碼範例示範如何使用SingleOrDefault<TSource>(IEnumerable<TSource>)選取唯一元素的陣列。The following code example demonstrates how to use SingleOrDefault<TSource>(IEnumerable<TSource>) to select the only element of an array.

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.
MsgBox("First array: " & result)

下列程式碼範例示範SingleOrDefault<TSource>(IEnumerable<TSource>)序列不包含只有一個項目時,會傳回預設值。The following code example demonstrates that SingleOrDefault<TSource>(IEnumerable<TSource>) returns a default value when the sequence does not contain exactly one element.

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)
MsgBox("Second array: " & output)

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

有時值default(TSource)不是您想要使用如果集合不包含任何元素的預設值。Sometimes the value of default(TSource) is not the default value that you want to use if the collection contains no elements. 除了檢查不必要的預設值的結果,並將它如有必要變更,您可以使用DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)方法,以指定您想要使用這個集合是空的預設值。Instead of checking the result for the unwanted default value and then changing it if necessary, you can use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method to specify the default value that you want to use if the collection is empty. 然後,呼叫Single<TSource>(IEnumerable<TSource>)若要取得的項目。Then, call Single<TSource>(IEnumerable<TSource>) to obtain the element. 下列程式碼範例會使用這兩種技術以取得預設值為 1,如果頁面號碼的集合是空的。The following code example uses both techniques to obtain a default value of 1 if a collection of page numbers is empty. 整數,預設值為 0,這是通常是有效的頁面編號,因為預設值必須被指定為 1。Because the default value for an integer is 0, which is not usually a valid page number, the default value must be specified as 1 instead. 查詢完成執行後不必要的預設值會檢查第一個結果變數。The first result variable is checked for the unwanted default value after the query has finished executing. 第二個結果變數使用取得的DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)指定預設值為 1。The second result variable is obtained by using DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) to specify a default value of 1.

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
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.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

備註

參考和可為 null 類型的預設值是nullThe default value for reference and nullable types is null.

SingleOrDefault方法不會提供方法來指定預設值。The SingleOrDefault method does not provide a way to specify a default value. 如果您想要指定預設值以外default(TSource),使用DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)範例 > 一節中所述的方法。If you want to specify a default value other than default(TSource), use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.

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

傳回序列中符合指定之條件的唯一一個元素,如果沒有這類元素,則為預設值,如果有一個以上的元素符合條件,這個方法就會擲回例外狀況。Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.

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);
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 項目的類型。The type of the elements of source.

參數

source
IEnumerable<TSource>

IEnumerable<T>傳回單一項目。An IEnumerable<T> to return a single element from.

predicate
Func<TSource,Boolean>

用來測試項目是否符合條件的函式。A function to test an element for a condition.

傳回

TSource TSource TSource TSource

輸入序列中符合條件的單一項目或default(TSource) 如果找到這類項目。The single element of the input sequence that satisfies the condition, or default(TSource) if no such element is found.

例外狀況

sourcepredicatenullsource or predicate is null.

多個項目符合條件中的predicateMore than one element satisfies the condition in predicate.

範例

下列程式碼範例示範如何使用SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)選取陣列中符合條件的唯一項目。The following code example demonstrates how to use SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) to select the only element of an array that satisfies a condition.

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.
MsgBox("First array: " & fruit1)

下列程式碼範例示範SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)序列不包含只有一個符合條件的項目時,會傳回預設值。The following code example demonstrates that SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) returns a default value when the sequence does not contain exactly one element that satisfies the condition.

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)
MsgBox("Second array: " & output)

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

備註

參考和可為 null 類型的預設值是nullThe default value for reference and nullable types is null.

適用於