Enumerable.SingleOrDefault Método
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Retornará um único elemento específico de uma sequência ou um valor padrão se esse elemento não for encontrado.
SingleOrDefault<TSource>(IEnumerable<TSource>) |
Retorna o único elemento de uma sequência ou um valor padrão se a sequência é vazia; esse método gera uma exceção se há mais de um elemento na sequência. |
SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Retorna o único elemento de uma sequência que satisfaz uma condição especificada ou um valor padrão se esse elemento não existir. Esse método lança uma exceção se mais de um elemento satisfizer a condição. |
SingleOrDefault<TSource>(IEnumerable<TSource>, TSource) |
Retorna o único elemento de uma sequência ou um valor padrão especificado se a sequência estiver vazia; esse método gerará uma exceção se houver mais de um elemento na sequência. |
SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource) |
Retorna o único elemento de uma sequência que atende a uma condição especificada ou um valor padrão especificado se esse elemento não existir; esse método gerará uma exceção se mais de um elemento atender à condição. |
- Origem:
- Single.cs
- Origem:
- Single.cs
- Origem:
- Single.cs
Retorna o único elemento de uma sequência ou um valor padrão se a sequência é vazia; esse método gera uma exceção se há mais de um elemento na sequência.
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
Parâmetros de tipo
- TSource
O tipo dos elementos de source
.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> do qual o único elemento será retornado.
Retornos
O único elemento da sequência de entrada, ou default
(TSource
), se a sequência não contiver elementos.
Exceções
source
é null
.
A sequência de entrada contém mais de um elemento.
Exemplos
O exemplo de código a seguir demonstra como usar SingleOrDefault<TSource>(IEnumerable<TSource>) para selecionar o único elemento de uma matriz.
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}")
O exemplo de código a seguir demonstra que SingleOrDefault<TSource>(IEnumerable<TSource>) retorna um valor padrão quando a sequência está vazia.
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
Às vezes, o valor de default(TSource)
não é o valor padrão que você deseja usar se a coleção não contiver elementos. Em vez de verificar o resultado do valor padrão indesejado e alterá-lo, se necessário, você pode usar o DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) método para especificar o valor padrão que deseja usar se a coleção estiver vazia. Em seguida, chame Single<TSource>(IEnumerable<TSource>) para obter o elemento . O exemplo de código a seguir usa 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 geralmente 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 quanto ao valor padrão indesejado após a conclusão da execução da consulta. A segunda variável de resultado é obtida usando DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) para especificar um valor padrão de 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
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
Comentários
O valor padrão para tipos de referência e anuláveis é null
.
O SingleOrDefault método não fornece uma maneira de especificar um valor padrão. Se você quiser especificar um valor padrão diferente de default(TSource)
, use o DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) método , conforme descrito na seção Exemplo.
Aplica-se a
.NET 9 e outras versões
Produto | Versões |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
- Origem:
- Single.cs
- Origem:
- Single.cs
- Origem:
- Single.cs
Retorna o único elemento de uma sequência que satisfaz uma condição especificada ou um valor padrão se esse elemento não existir. Esse método lança uma exceção se mais de um elemento satisfizer a condição.
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
Parâmetros de tipo
- TSource
O tipo dos elementos de source
.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> do qual retornar um único elemento.
Retornos
O único elemento da sequência de entrada que atende à condição ou default
(TSource
) se esse elemento não for encontrado.
Exceções
source
ou predicate
é null
.
Mais de um elemento satisfaz a condição na predicate
.
Exemplos
O exemplo de código a seguir demonstra como usar SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) para selecionar o único elemento de uma matriz que satisfaça uma condição.
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}")
O exemplo de código a seguir demonstra que SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) retorna um valor padrão quando a sequência não contém elementos que atendam à condição.
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
Comentários
O valor padrão para tipos de referência e anuláveis é null
.
Aplica-se a
.NET 9 e outras versões
Produto | Versões |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
- Origem:
- Single.cs
- Origem:
- Single.cs
- Origem:
- Single.cs
Retorna o único elemento de uma sequência ou um valor padrão especificado se a sequência estiver vazia; esse método gerará uma exceção se houver mais de um elemento na sequência.
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
Parâmetros de tipo
- TSource
O tipo dos elementos de source
.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> do qual o único elemento será retornado.
- defaultValue
- TSource
O valor padrão a ser retornado se a sequência estiver vazia.
Retornos
O único elemento da sequência de entrada ou defaultValue
se a sequência não contiver elementos.
Exceções
source
é null
.
A sequência de entrada contém mais de um elemento.
Aplica-se a
.NET 9 e outras versões
Produto | Versões |
---|---|
.NET | 6, 7, 8, 9 |
- Origem:
- Single.cs
- Origem:
- Single.cs
- Origem:
- Single.cs
Retorna o único elemento de uma sequência que atende a uma condição especificada ou um valor padrão especificado se esse elemento não existir; esse método gerará uma exceção se mais de um elemento atender à condição.
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
Parâmetros de tipo
- TSource
O tipo dos elementos de source
.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> do qual retornar um único elemento.
- defaultValue
- TSource
O valor padrão a ser retornado se a sequência estiver vazia.
Retornos
O único elemento da sequência de entrada que satisfaz a condição ou defaultValue
se nenhum elemento desse tipo for encontrado.
Exceções
source
ou predicate
é null
.
Mais de um elemento satisfaz a condição na predicate
.
Aplica-se a
.NET 9 e outras versões
Produto | Versões |
---|---|
.NET | 6, 7, 8, 9 |
Comentários do .NET
O .NET é um projeto código aberto. Selecione um link para fornecer comentários: