Queryable.SingleOrDefault Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Devolve um único elemento específico de uma sequência, ou um valor padrão se tal elemento não for encontrado.
Sobrecargas
| Name | Description |
|---|---|
| SingleOrDefault<TSource>(IQueryable<TSource>) |
Devolve o único elemento de uma sequência, ou um valor padrão se a sequência estiver vazia; este método lança uma exceção se houver mais do que um elemento na sequência. |
| SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) |
Devolve o único elemento de uma sequência que satisfaz uma condição especificada ou um valor padrão se tal elemento não existir; este método lança uma exceção se mais do que um elemento satisfizerem a condição. |
SingleOrDefault<TSource>(IQueryable<TSource>)
Devolve o único elemento de uma sequência, ou um valor padrão se a sequência estiver vazia; este método lança uma exceção se houver mais do que um elemento na sequência.
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
Parâmetros de Tipo Genérico
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IQueryable<TSource>
E IQueryable<T> para devolver o elemento único de .
Devoluções
O elemento único da sequência de entrada, ou default(TSource) se a sequência não contiver elementos.
Exceções
source é null.
source tem mais do que um elemento.
Exemplos
O exemplo de código seguinte demonstra como selecionar SingleOrDefault<TSource>(IQueryable<TSource>) o único elemento de um array. A segunda consulta demonstra que SingleOrDefault<TSource>(IQueryable<TSource>) devolve um valor por defeito quando a sequência não contém exatamente um elemento.
// 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!
Por vezes, o valor de default(TSource) não é o valor padrão que pretende usar se a coleção não contiver elementos. Em vez de verificar o resultado para o valor padrão indesejado e depois alterá-lo se necessário, podes usar o DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) método para especificar o valor padrão que queres usar se a coleção estiver vazia. Depois, chame Single<TSource>(IQueryable<TSource>) para obter o elemento. O exemplo de código seguinte utiliza ambas as técnicas para obter um valor padrão de 1 se uma coleção de números de página estiver vazia. Como o valor padrão de um inteiro é 0, que normalmente não é um número de página válido, o valor padrão deve ser especificado como 1. A primeira variável de resultado é verificada para o valor padrão indesejado após a conclusão da consulta. A segunda variável de resultado é obtida ao chamar DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) para especificar um valor padrão de 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
Observações
O SingleOrDefault<TSource>(IQueryable<TSource>) método gera um MethodCallExpression que representa o autodenominado SingleOrDefault<TSource>(IQueryable<TSource>) como um método genérico construído. Depois passa o MethodCallExpression para o Execute<TResult>(Expression) método de o IQueryProvider representado pela Provider propriedade do source parâmetro.
O comportamento de consulta que ocorre como resultado da execução de uma árvore de expressões que representa a chamada SingleOrDefault<TSource>(IQueryable<TSource>) depende da implementação do tipo do source parâmetro. O comportamento esperado é que devolva o único elemento em source, ou um valor padrão se source for vazio.
O SingleOrDefault método não fornece uma forma de especificar um valor predefinido. Se quiser especificar um valor padrão diferente de default(TSource), use o DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) método conforme descrito na secção Exemplo.
Aplica-se a
SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)
Devolve o único elemento de uma sequência que satisfaz uma condição especificada ou um valor padrão se tal elemento não existir; este método lança uma exceção se mais do que um elemento satisfizerem a condição.
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
Parâmetros de Tipo Genérico
- TSource
O tipo dos elementos de source.
Parâmetros
- source
- IQueryable<TSource>
E IQueryable<T> para devolver um único elemento de.
- predicate
- Expression<Func<TSource,Boolean>>
Uma função para testar um elemento para uma condição.
Devoluções
O elemento único da sequência de entrada que satisfaz a condição em predicate, ou default(TSource) se tal elemento não for encontrado.
Exceções
source ou predicate é null.
Mais do que um elemento satisfaz a condição em predicate.
Exemplos
O exemplo de código seguinte demonstra como usar SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) para selecionar o único elemento de um array que satisfaz uma condição. A segunda consulta demonstra que SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) devolve um valor por defeito quando a sequência não contém exatamente um elemento que satisfaz a condição.
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!
Observações
Este método tem pelo menos um parâmetro de tipo Expression<TDelegate> cujo argumento de tipo é um dos Func<T,TResult> tipos. Para estes parâmetros, pode-se passar uma expressão lambda e ela será compilada para um Expression<TDelegate>.
O SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) método gera um MethodCallExpression que representa o autodenominado SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) como um método genérico construído. Depois passa o MethodCallExpression para o Execute<TResult>(Expression) método de o IQueryProvider representado pela Provider propriedade do source parâmetro.
O comportamento de consulta que ocorre como resultado da execução de uma árvore de expressões que representa a chamada SingleOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) depende da implementação do tipo do source parâmetro. O comportamento esperado é que devolve o único elemento em source que satisfaz a condição especificada por predicate, ou um valor padrão se tal elemento não existir.