Queryable.SingleOrDefault Queryable.SingleOrDefault Queryable.SingleOrDefault Queryable.SingleOrDefault Method

Definition

シーケンスの 1 つの特定の要素を返します。そのような要素が見つからない場合は既定値を返します。 Returns a single, specific element of a sequence, or a default value if no such element is found.

Overloads

SingleOrDefault<TSource>(IQueryable<TSource>) SingleOrDefault<TSource>(IQueryable<TSource>) SingleOrDefault<TSource>(IQueryable<TSource>) SingleOrDefault<TSource>(IQueryable<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>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) SingleOrDefault<TSource>(IQueryable<TSource>, Expression<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>(IQueryable<TSource>) SingleOrDefault<TSource>(IQueryable<TSource>) SingleOrDefault<TSource>(IQueryable<TSource>) SingleOrDefault<TSource>(IQueryable<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::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

Type Parameters

TSource

要素の型ソースします。 The type of the elements of source.

パラメーター

source
IQueryable<TSource>

1 つの要素を返す IQueryable<T> An IQueryable<T> to return the single element of.

Returns

TSource TSource TSource TSource

入力シーケンスの唯一の要素、または、シーケンスに要素が含まれない場合は default(TSource)。 The single element of the input sequence, or default(TSource) if the sequence contains no elements.

Exceptions

source には複数の要素があります。 source has more than one element.

Examples

次のコード例は、使用する方法を示しますSingleOrDefault<TSource>(IQueryable<TSource>)を配列の唯一の要素を選択します。The following code example demonstrates how to use SingleOrDefault<TSource>(IQueryable<TSource>) to select the only element of an array. 2 番目のクエリSingleOrDefault<TSource>(IQueryable<TSource>)シーケンスに正確に 1 つの要素が含まれていない場合は、既定値を返します。The second query demonstrates that SingleOrDefault<TSource>(IQueryable<TSource>) returns a default value when the sequence does not contain exactly one element.

// 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)コレクションに要素が含まれていない場合は、使用する既定値はありません。Sometimes the value of default(TSource) is not the default value that you want to use if the collection contains no elements. 不要な既定値の結果をチェックし、必要に応じてを変更して、代わりに使用することができます、DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)コレクションが空の場合に使用する既定値を指定します。Instead of checking the result for the unwanted default value and then changing it if necessary, you can use the DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) method to specify the default value that you want to use if the collection is empty. 次に呼び出すSingle<TSource>(IQueryable<TSource>)要素を取得します。Then, call Single<TSource>(IQueryable<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 is completed. 2 番目の結果変数が呼び出すことによって取得DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)1 の既定値を指定します。The second result variable is obtained by calling DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) to specify a default value of 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

Remarks

SingleOrDefault<TSource>(IQueryable<TSource>)メソッドを生成、MethodCallExpression呼び出しを表すSingleOrDefault<TSource>(IQueryable<TSource>)として構築されたジェネリック メソッド自体。The SingleOrDefault<TSource>(IQueryable<TSource>) method generates a MethodCallExpression that represents calling SingleOrDefault<TSource>(IQueryable<TSource>) itself as a constructed generic method. これは、後、渡します、MethodCallExpressionExecute<TResult>(Expression)のメソッド、IQueryProviderによって表される、Providerのプロパティ、sourceパラメーター。It then passes the MethodCallExpression to the Execute<TResult>(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

呼び出し元を表す式ツリーを実行した結果として発生するクエリの動作SingleOrDefault<TSource>(IQueryable<TSource>)の型の実装によって異なります、sourceパラメーター。The query behavior that occurs as a result of executing an expression tree that represents calling SingleOrDefault<TSource>(IQueryable<TSource>) depends on the implementation of the type of the source parameter. 想定される動作では、唯一の要素を返しますsource、既定値の場合は値またはsourceが空です。The expected behavior is that it returns the only element in source, or a default value if source is empty.

SingleOrDefaultメソッドが既定値を指定する方法を提供していません。The SingleOrDefault method does not provide a way to specify a default value. 以外の既定値を指定したい場合default(TSource)を使用して、DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)メソッドの使用例」で説明します。If you want to specify a default value other than default(TSource), use the DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) method as described in the Example section.

SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) SingleOrDefault<TSource>(IQueryable<TSource>, Expression<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::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

Type Parameters

TSource

要素の型ソースします。 The type of the elements of source.

パラメーター

source
IQueryable<TSource>

1 つの要素を返す IQueryable<T> An IQueryable<T> to return a single element from.

predicate
Expression<Func<TSource,Boolean>>

要素が条件を満たしているかどうかをテストする関数。 A function to test an element for a condition.

Returns

TSource TSource TSource TSource

predicate の条件を満たす入力シーケンスの唯一要素、または、そのような要素が見つからない場合は default(TSource)。 The single element of the input sequence that satisfies the condition in predicate, or default(TSource) if no such element is found.

Exceptions

source または predicatenull です。 source or predicate is null.

predicate の条件を満たす要素が複数あります。 More than one element satisfies the condition in predicate.

Examples

次のコード例は、使用する方法を示しますSingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)条件を満たす、配列の唯一の要素を選択します。The following code example demonstrates how to use SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) to select the only element of an array that satisfies a condition. 2 番目のクエリSingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)シーケンスに条件を満たす要素が 1 つだけが含まれていない場合は、既定値を返します。The second query demonstrates that SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) returns a default value when the sequence does not contain exactly one element that satisfies the condition.

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!

Remarks

このメソッドは、少なくとも 1 つのパラメーター型のExpression<TDelegate>型引数は、のいずれか、Func<T,TResult>型。This method has at least one parameter of type Expression<TDelegate> whose type argument is one of the Func<T,TResult> types. ラムダ式で、これらのパラメーターを渡すことができますにコンパイルされると、Expression<TDelegate>します。For these parameters, you can pass in a lambda expression and it will be compiled to an Expression<TDelegate>.

SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)メソッドを生成、MethodCallExpression呼び出しを表すSingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)として構築されたジェネリック メソッド自体。The SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) method generates a MethodCallExpression that represents calling SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) itself as a constructed generic method. これは、後、渡します、MethodCallExpressionExecute<TResult>(Expression)のメソッド、IQueryProviderによって表される、Providerのプロパティ、sourceパラメーター。It then passes the MethodCallExpression to the Execute<TResult>(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

呼び出し元を表す式ツリーを実行した結果として発生するクエリの動作SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)の型の実装によって異なります、sourceパラメーター。The query behavior that occurs as a result of executing an expression tree that represents calling SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) depends on the implementation of the type of the source parameter. 想定される動作では、唯一の要素を返しますsourceによって指定された条件を満たすpredicate、またはこのような要素が存在しない場合は、既定値。The expected behavior is that it returns the only element in source that satisfies the condition specified by predicate, or a default value if no such element exists.

Applies to