Queryable.DefaultIfEmpty Método

Definición

Devuelve los elementos de una secuencia o una colección singleton con valores predeterminados si la secuencia está vacía.Returns the elements in a sequence or a default valued singleton collection if the sequence is empty.

Sobrecargas

DefaultIfEmpty<TSource>(IQueryable<TSource>)

Devuelve los elementos de la secuencia especificada o el valor predeterminado del parámetro de tipo en una colección singleton si la secuencia está vacía.Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.

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

Devuelve los elementos de la secuencia especificada o el valor especificado en una colección singleton si la secuencia está vacía.Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

DefaultIfEmpty<TSource>(IQueryable<TSource>)

Devuelve los elementos de la secuencia especificada o el valor predeterminado del parámetro de tipo en una colección singleton si la secuencia está vacía.Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.

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);
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

Tipo de los elementos de source.The type of the elements of source.

Parámetros

source
IQueryable<TSource>

IQueryable<T> para el que se va a devolver un valor predeterminado si está vacío.The IQueryable<T> to return a default value for if empty.

Devoluciones

IQueryable<TSource>

IQueryable<T> que contiene default(TSource) si source está vacío; de lo contrario, source.An IQueryable<T> that contains default(TSource) if source is empty; otherwise, source.

Excepciones

source es null.source is null.

Ejemplos

En los siguientes ejemplos de código se muestra cómo usar DefaultIfEmpty<TSource>(IQueryable<TSource>) para proporcionar un valor predeterminado en caso de que la secuencia de origen esté vacía.The following code examples demonstrate how to use DefaultIfEmpty<TSource>(IQueryable<TSource>) to provide a default value in case the source sequence is empty.

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

Comentarios

El DefaultIfEmpty<TSource>(IQueryable<TSource>) método genera un MethodCallExpression que representa la llamada a DefaultIfEmpty<TSource>(IQueryable<TSource>) sí mismo como un método genérico construido.The DefaultIfEmpty<TSource>(IQueryable<TSource>) method generates a MethodCallExpression that represents calling DefaultIfEmpty<TSource>(IQueryable<TSource>) itself as a constructed generic method. A continuación, pasa el MethodCallExpression al CreateQuery<TElement>(Expression) método de IQueryProvider representado por la Provider propiedad del source parámetro.It then passes the MethodCallExpression to the CreateQuery<TElement>(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

El comportamiento de la consulta que se produce como resultado de ejecutar un árbol de expresión que representa DefaultIfEmpty<TSource>(IQueryable<TSource>) la llamada depende de la implementación del tipo del source parámetro.The query behavior that occurs as a result of executing an expression tree that represents calling DefaultIfEmpty<TSource>(IQueryable<TSource>) depends on the implementation of the type of the source parameter. El comportamiento esperado es que devuelva source si no está vacío.The expected behavior is that it returns source if it is not empty. De lo contrario, devuelve un IQueryable<T> que contiene default(TSource) .Otherwise, it returns an IQueryable<T> that contains default(TSource).

Se aplica a

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

Devuelve los elementos de la secuencia especificada o el valor especificado en una colección singleton si la secuencia está vacía.Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

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

Tipo de los elementos de source.The type of the elements of source.

Parámetros

source
IQueryable<TSource>

IQueryable<T> para el que se va a devolver el valor especificado si está vacío.The IQueryable<T> to return the specified value for if empty.

defaultValue
TSource

Valor que se va a devolver si la secuencia está vacía.The value to return if the sequence is empty.

Devoluciones

IQueryable<TSource>

IQueryable<T> que contiene defaultValue si source está vacío; de lo contrario, source.An IQueryable<T> that contains defaultValue if source is empty; otherwise, source.

Excepciones

source es null.source is null.

Ejemplos

En el ejemplo de código siguiente se muestra una situación en la que resulta útil llamar a DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) en una LINQLINQ consulta.The following code example shows a situation in which it is useful to call DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) in a LINQLINQ query. En este ejemplo, se pasa un valor predeterminado DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) .A default value is passed to DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) in this example.

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

Comentarios

El DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) método genera un MethodCallExpression que representa la llamada a DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) sí mismo como un método genérico construido.The DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) method generates a MethodCallExpression that represents calling DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) itself as a constructed generic method. A continuación, pasa el MethodCallExpression al CreateQuery<TElement>(Expression) método de IQueryProvider representado por la Provider propiedad del source parámetro.It then passes the MethodCallExpression to the CreateQuery<TElement>(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

El comportamiento de la consulta que se produce como resultado de ejecutar un árbol de expresión que representa DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) la llamada depende de la implementación del tipo del source parámetro.The query behavior that occurs as a result of executing an expression tree that represents calling DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) depends on the implementation of the type of the source parameter. El comportamiento esperado es que devuelva source si no está vacío.The expected behavior is that it returns source if it is not empty. De lo contrario, devuelve un IQueryable<T> que contiene defaultValue .Otherwise, it returns an IQueryable<T> that contains defaultValue.

Se aplica a