Queryable.DefaultIfEmpty Método

Definição

Retornará os elementos em uma sequência ou uma coleção de singletons com valor padrão se a sequência estiver vazia.

Sobrecargas

DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)

Retorna os elementos da sequência especificada ou o valor especificado em uma coleção de singletons se a sequência está vazia.

DefaultIfEmpty<TSource>(IQueryable<TSource>)

Retornará os elementos da sequência especificada ou o valor padrão do parâmetro de tipo em uma coleção de singletons se a sequência estiver vazia.

DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)

Origem:
Queryable.cs
Origem:
Queryable.cs
Origem:
Queryable.cs

Retorna os elementos da sequência especificada ou o valor especificado em uma coleção de singletons se a sequência está vazia.

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

Parâmetros de tipo

TSource

O tipo dos elementos de source.

Parâmetros

source
IQueryable<TSource>

O IQueryable<T> para o qual será retornado o valor especificado se ele estiver vazio.

defaultValue
TSource

O valor a ser retornado se a sequência estiver vazia.

Retornos

IQueryable<TSource>

Um IQueryable<T> que contém defaultValue se source está vazio; caso contrário, source.

Exceções

source é null.

Exemplos

O exemplo de código a seguir mostra uma situação em que é útil chamar DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) em uma consulta LINQ. Um valor padrão é passado para DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) neste exemplo.

// Create a list of Pet objects.
List<Pet> pets =
    new List<Pet>{ new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };

// This query selects only those pets that are 10 or older.
// In case there are no pets that meet that criteria, call
// DefaultIfEmpty(). This code passes an (optional) default
// value to DefaultIfEmpty().
string[] oldPets =
    pets.AsQueryable()
    .Where(pet => pet.Age >= 10)
    .Select(pet => pet.Name)
    .DefaultIfEmpty("[EMPTY]")
    .ToArray();

Console.WriteLine("First query: " + oldPets[0]);

// This query selects only those pets that are 10 or older.
// This code does not call DefaultIfEmpty().
string[] oldPets2 =
    pets.AsQueryable()
    .Where(pet => pet.Age >= 10)
    .Select(pet => pet.Name)
    .ToArray();

// There may be no elements in the array, so directly
// accessing element 0 may throw an exception.
try
{
    Console.WriteLine("Second query: " + oldPets2[0]);
}
catch (Exception e)
{
    Console.WriteLine("Second query: An exception was thrown: " + e.Message);
}

/*
    This code produces the following output:

    First query: [EMPTY]
    Second query: An exception was thrown: Index was outside the bounds of the array.
*/
' Create a list of Pet objects.
Dim pets As New List(Of Pet)(New Pet() { _
                   New Pet With {.Name = "Barley", .Age = 8}, _
                   New Pet With {.Name = "Boots", .Age = 4}, _
                   New Pet With {.Name = "Whiskers", .Age = 1}})

' This query returns pets that are 10 or older. In case there are no pets 
' that meet that criteria, call DefaultIfEmpty(). This code passes an (optional) 
' default value to DefaultIfEmpty().
Dim oldPets() As String = pets.AsQueryable() _
    .Where(Function(Pet) Pet.Age >= 10) _
    .Select(Function(Pet) Pet.Name) _
    .DefaultIfEmpty("[EMPTY]") _
    .ToArray()
Try
    MsgBox("First query: " + oldPets(0))
Catch ex As Exception
    Console.WriteLine("First query: An exception was thrown: " + ex.Message)
End Try

' This query selects only those pets that are 10 or older.
' This code does not call DefaultIfEmpty().
Dim oldPets2() As String = _
    pets.AsQueryable() _
    .Where(Function(Pet) Pet.Age >= 10) _
    .Select(Function(Pet) Pet.Name) _
    .ToArray()

' There may be no elements in the array, so directly
' accessing element 0 may throw an exception.
Try
    MsgBox("Second query: " + oldPets2(0))
Catch ex As Exception
    MsgBox("Second query: An exception was thrown: " + ex.Message)
End Try

' This code produces the following output:
'
' First(query) : [EMPTY]
' Second query: An exception was thrown: Index was outside the bounds of the array.

Comentários

O DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) método gera um MethodCallExpression que representa a própria chamada DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) como um método genérico construído. Em seguida, ele passa o MethodCallExpression para o CreateQuery<TElement>(Expression) método do IQueryProvider representado pela Provider propriedade do source parâmetro .

O comportamento da consulta que ocorre como resultado da execução de uma árvore de expressão que representa a chamada DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) depende da implementação do tipo do source parâmetro. O comportamento esperado é que ele retornará source se não estiver vazio. Caso contrário, ele retornará um IQueryable<T> que contém defaultValue.

Aplica-se a

DefaultIfEmpty<TSource>(IQueryable<TSource>)

Origem:
Queryable.cs
Origem:
Queryable.cs
Origem:
Queryable.cs

Retornará os elementos da sequência especificada ou o valor padrão do parâmetro de tipo em uma coleção de singletons se a sequência estiver vazia.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TSource> ^ DefaultIfEmpty(System::Linq::IQueryable<TSource> ^ source);
public static System.Linq.IQueryable<TSource> DefaultIfEmpty<TSource> (this System.Linq.IQueryable<TSource> source);
public static System.Linq.IQueryable<TSource?> DefaultIfEmpty<TSource> (this System.Linq.IQueryable<TSource> source);
static member DefaultIfEmpty : System.Linq.IQueryable<'Source> -> System.Linq.IQueryable<'Source>
<Extension()>
Public Function DefaultIfEmpty(Of TSource) (source As IQueryable(Of TSource)) As IQueryable(Of TSource)

Parâmetros de tipo

TSource

O tipo dos elementos de source.

Parâmetros

source
IQueryable<TSource>

O IQueryable<T> para o qual será retornado um valor padrão se estiver vazio.

Retornos

IQueryable<TSource>

Um IQueryable<T> que contém default (TSource) se source estiver vazio; caso contrário, source.

Exceções

source é null.

Exemplos

Os exemplos de código a seguir demonstram como usar DefaultIfEmpty<TSource>(IQueryable<TSource>) para fornecer um valor padrão caso a sequência de origem esteja vazia.

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void DefaultIfEmptyEx1()
{
    // Create a list of Pet objects.
    List<Pet> pets =
        new List<Pet>{ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };

    // Call DefaultIfEmtpy() on the collection that Select()
    // returns, so that if the initial list is empty, there
    // will always be at least one item in the returned array.
    string[] names =
        pets.AsQueryable()
        .Select(pet => pet.Name)
        .DefaultIfEmpty()
        .ToArray();

    string first = names[0];
    Console.WriteLine(first);
}

/*
    This code produces the following output:

    Barley
*/
Structure Pet
    Public Name As String
    Public Age As Integer
End Structure

Shared Sub DefaultIfEmptyEx1()
    ' Create a list of Pet objects.
    Dim pets As New List(Of Pet)(New Pet() { _
                        New Pet With {.Name = "Barley", .Age = 8}, _
                        New Pet With {.Name = "Boots", .Age = 4}, _
                        New Pet With {.Name = "Whiskers", .Age = 1}})

    ' Call DefaultIfEmtpy() on the collection that Select()
    ' returns, so that if the initial list is empty, there
    ' will always be at least one item in the returned array.
    Dim names() As String = pets.AsQueryable() _
        .Select(Function(Pet) Pet.Name) _
        .DefaultIfEmpty() _
        .ToArray()

    Dim first As String = names(0)
    MsgBox(first)

    ' This code produces the following output:
    '
    ' Barley

End Sub

Comentários

O DefaultIfEmpty<TSource>(IQueryable<TSource>) método gera um MethodCallExpression que representa a própria chamada DefaultIfEmpty<TSource>(IQueryable<TSource>) como um método genérico construído. Em seguida, ele passa o MethodCallExpression para o CreateQuery<TElement>(Expression) método do IQueryProvider representado pela Provider propriedade do source parâmetro .

O comportamento da consulta que ocorre como resultado da execução de uma árvore de expressão que representa a chamada DefaultIfEmpty<TSource>(IQueryable<TSource>) depende da implementação do tipo do source parâmetro. O comportamento esperado é que ele retornará source se não estiver vazio. Caso contrário, ele retornará um IQueryable<T> que contém default(TSource).

Aplica-se a