Queryable.Single Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает один, определенный элемент последовательности.
Перегрузки
| Имя | Описание |
|---|---|
| Single<TSource>(IQueryable<TSource>) |
Возвращает единственный элемент последовательности и создает исключение, если в последовательности нет ни одного элемента. |
| Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) |
Возвращает единственный элемент последовательности, удовлетворяющей указанному условию, и создает исключение, если существует несколько таких элементов. |
Single<TSource>(IQueryable<TSource>)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Возвращает единственный элемент последовательности и создает исключение, если в последовательности нет ни одного элемента.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource Single(System::Linq::IQueryable<TSource> ^ source);
public static TSource Single<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 TSource Single<TSource>(this System.Linq.IQueryable<TSource> source);
static member Single : System.Linq.IQueryable<'Source> -> '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 Single : System.Linq.IQueryable<'Source> -> 'Source
<Extension()>
Public Function Single(Of TSource) (source As IQueryable(Of TSource)) As TSource
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IQueryable<TSource>
Значение, IQueryable<T> возвращаемое одним элементом.
Возвращаемое значение
Один элемент входной последовательности.
- Атрибуты
Исключения
source равно null.
source имеет несколько элементов.
–или–
Исходная последовательность пуста.
Примеры
В следующем примере кода показано, как выбрать Single<TSource>(IQueryable<TSource>) единственный элемент массива.
// Create two arrays.
string[] fruits1 = { "orange" };
string[] fruits2 = { "orange", "apple" };
// Get the only item in the first array.
string fruit1 = fruits1.AsQueryable().Single();
Console.WriteLine("First query: " + fruit1);
try
{
// Try to get the only item in the second array.
string fruit2 = fruits2.AsQueryable().Single();
Console.WriteLine("Second query: " + fruit2);
}
catch (System.InvalidOperationException)
{
Console.WriteLine(
"Second query: The collection does not contain exactly one element."
);
}
/*
This code produces the following output:
First query: orange
Second query: The collection does not contain exactly one element
*/
' Create two arrays.
Dim fruits1() As String = {"orange"}
Dim fruits2() As String = {"orange", "apple"}
' Get the only item in the first array.
Dim result As String = fruits1.AsQueryable().Single()
' Display the result.
MsgBox("First query: " & result)
Try
' Try to get the only item in the second array.
Dim fruit2 As String = fruits2.AsQueryable().Single()
MsgBox("Second query: " + fruit2)
Catch
MsgBox("Second query: The collection does not contain exactly one element.")
End Try
' This code produces the following output:
' First query: orange
' Second query: The collection does not contain exactly one element.
Комментарии
Метод Single<TSource>(IQueryable<TSource>) создает объект MethodCallExpression , представляющий Single<TSource>(IQueryable<TSource>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Single<TSource>(IQueryable<TSource>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает единственный элемент в source.
Применяется к
Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
- Исходный код:
- Queryable.cs
Возвращает единственный элемент последовательности, удовлетворяющей указанному условию, и создает исключение, если существует несколько таких элементов.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource Single(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static TSource Single<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
[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 TSource Single<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member Single : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> '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 Single : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
<Extension()>
Public Function Single(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As TSource
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IQueryable<TSource>
Объект, IQueryable<T> из который возвращается один элемент.
- predicate
- Expression<Func<TSource,Boolean>>
Функция для тестирования элемента для условия.
Возвращаемое значение
Один элемент входной последовательности, удовлетворяющий условию predicate.
- Атрибуты
Исключения
source или predicate есть null.
Элемент не удовлетворяет условию в predicate.
–или–
Несколько элементов удовлетворяют условию в predicate.
–или–
Исходная последовательность пуста.
Примеры
В следующем примере кода показано, как использовать Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) для выбора единственного элемента массива, удовлетворяющего условию.
string[] fruits = { "apple", "banana", "mango",
"orange", "passionfruit", "grape" };
// Get the only string in the array whose length is greater than 10.
string fruit1 = fruits.AsQueryable().Single(fruit => fruit.Length > 10);
Console.WriteLine("First Query: " + fruit1);
try
{
// Try to get the only string in the array
// whose length is greater than 15.
string fruit2 = fruits.AsQueryable().Single(fruit => fruit.Length > 15);
Console.WriteLine("Second Query: " + fruit2);
}
catch (System.InvalidOperationException)
{
Console.Write("Second Query: The collection does not contain ");
Console.WriteLine("exactly one element whose length is greater than 15.");
}
/*
This code produces the following output:
First Query: passionfruit
Second Query: The collection does not contain exactly one
element whose length is greater than 15.
*/
Dim fruits() As String = _
{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
' Get the only string in the array whose length is greater than 10.
Dim result As String = _
fruits.AsQueryable().Single(Function(fruit) fruit.Length > 10)
' Display the result.
MsgBox("First Query: " & result)
Try
' Try to get the only string in the array
' whose length is greater than 15.
Dim fruit2 As String = fruits.AsQueryable().Single(Function(fruit) fruit.Length > 15)
MsgBox("Second Query: " + fruit2)
Catch
Dim text As String = "Second Query: The collection does not contain "
text = text & "exactly one element whose length is greater than 15."
MsgBox(text)
End Try
' This code produces the following output:
' First Query: passionfruit
' Second Query: The collection does not contain exactly one
' element whose length is greater than 15.
Комментарии
Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.
Метод Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) создает объект MethodCallExpression , представляющий Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.
Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, что он возвращает единственный элемент, который source удовлетворяет условию, указанному predicateв .