Queryable.DefaultIfEmpty Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает элементы в последовательности или по умолчанию значение одноэлементной коллекции, если последовательность пуста.
Перегрузки
| Имя | Описание |
|---|---|
| DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) |
Возвращает элементы указанной последовательности или указанное значение в одной коллекции, если последовательность пуста. |
| DefaultIfEmpty<TSource>(IQueryable<TSource>) |
Возвращает элементы указанной последовательности или значение параметра типа по умолчанию в одной коллекции, если последовательность пуста. |
DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Возвращает элементы указанной последовательности или указанное значение в одной коллекции, если последовательность пуста.
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);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
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>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
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)
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IQueryable<TSource>
Возвращает IQueryable<T> указанное значение, если пустое.
- defaultValue
- TSource
Значение, возвращаемое, если последовательность пуста.
Возвращаемое значение
Значение IQueryable<T> , содержащее defaultValue , если source пусто; в противном случае source.
- Атрибуты
Исключения
source равно null.
Примеры
В следующем примере кода показана ситуация, в которой полезно вызывать запрос DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) LINQ. Значение по умолчанию передается DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) в этом примере.
// 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.
Комментарии
Метод DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) создает объект MethodCallExpression , представляющий DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<TElement>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращается source , если он не пуст. В противном случае возвращается содержащийся IQueryable<T>defaultValueобъект.
Применяется к
DefaultIfEmpty<TSource>(IQueryable<TSource>)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Возвращает элементы указанной последовательности или значение параметра типа по умолчанию в одной коллекции, если последовательность пуста.
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);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
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>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
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)
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IQueryable<TSource>
Возвращает IQueryable<T> значение по умолчанию, если пустое.
Возвращаемое значение
Значение IQueryable<T> , содержащее default() значение ,TSourceесли source пусто; в противном случае source.
- Атрибуты
Исключения
source равно null.
Примеры
В следующих примерах кода показано, как использовать DefaultIfEmpty<TSource>(IQueryable<TSource>) для предоставления значения по умолчанию в случае, если исходная последовательность пуста.
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
Комментарии
Метод DefaultIfEmpty<TSource>(IQueryable<TSource>) создает объект MethodCallExpression , представляющий DefaultIfEmpty<TSource>(IQueryable<TSource>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionCreateQuery<TElement>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов DefaultIfEmpty<TSource>(IQueryable<TSource>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращается source , если он не пуст. В противном случае возвращается содержащийся IQueryable<T>default(TSource)объект.