Enumerable.Single Метод

Определение

Возвращает единственный конкретный элемент последовательности.

Перегрузки

Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

Возвращает единственный элемент последовательности, удовлетворяющий указанному условию, и вызывает исключение, если таких элементов больше одного.

Single<TSource>(IEnumerable<TSource>)

Возвращает единственный элемент последовательности и генерирует исключение, если число элементов последовательности отлично от 1.

Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

Возвращает единственный элемент последовательности, удовлетворяющий указанному условию, и вызывает исключение, если таких элементов больше одного.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource Single(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate);
public static TSource Single<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
static member Single : seq<'Source> * Func<'Source, bool> -> 'Source
<Extension()>
Public Function Single(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean)) As TSource

Параметры типа

TSource

Тип элементов source.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T>, из которого требуется возвратить единственный элемент.

predicate
Func<TSource,Boolean>

Функция для проверки элемента на соответствие условию.

Возвращаемое значение

TSource

Единственный элемент входной последовательности, удовлетворяющий условию.

Исключения

Параметр source или predicate имеет значение null.

Ни один элемент не удовлетворяет условию предиката predicate.

-или-

Условию предиката predicate удовлетворяет более одного элемента.

-или-

Исходная последовательность пуста.

Примеры

В следующем примере кода показано, как использовать Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) для выбора единственного элемента массива, удовлетворяющего условию.

string[] fruits = { "apple", "banana", "mango",
                      "orange", "passionfruit", "grape" };

string fruit1 = fruits.Single(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 greater than 10.
Dim result As String =
fruits.Single(Function(fruit) fruit.Length > 10)

' Display the result.
Console.WriteLine($"First query: {result}")

В следующем примере кода показано, что Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) вызывает исключение, если последовательность не содержит ровно одного элемента, удовлетворяющего условию.

string fruit2 = null;

try
{
    fruit2 = fruits.Single(fruit => fruit.Length > 15);
}
catch (System.InvalidOperationException)
{
    Console.WriteLine(@"The collection does not contain exactly
                    one element whose length is greater than 15.");
}

Console.WriteLine(fruit2);

// This code produces the following output:
//
// The collection does not contain exactly
// one element whose length is greater than 15.
result = String.Empty

' Try to get the single item in the array whose length is > 15.
Try
    result = fruits.Single(Function(fruit) _
                           fruit.Length > 15)
Catch ex As System.InvalidOperationException
    result = "There is not EXACTLY ONE element whose length is > 15."
End Try

' Display the result.
Console.WriteLine($"Second query: {result}")

' This code produces the following output:
'
' First query: passionfruit
' Second query: There is not EXACTLY ONE element whose length is > 15.

Комментарии

Метод Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) создает исключение, если входная последовательность не содержит соответствующего элемента. Чтобы вместо этого возвращать, null если соответствующий элемент не найден, используйте .SingleOrDefault

Применяется к

Single<TSource>(IEnumerable<TSource>)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

Возвращает единственный элемент последовательности и генерирует исключение, если число элементов последовательности отлично от 1.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource Single(System::Collections::Generic::IEnumerable<TSource> ^ source);
public static TSource Single<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);
static member Single : seq<'Source> -> 'Source
<Extension()>
Public Function Single(Of TSource) (source As IEnumerable(Of TSource)) As TSource

Параметры типа

TSource

Тип элементов source.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T>, единственный элемент которого требуется возвратить.

Возвращаемое значение

TSource

Единственный элемент входной последовательности.

Исключения

source имеет значение null.

Входная последовательность содержит более одного элемента.

-или-

Входная последовательность пуста.

Примеры

В следующем примере кода показано, как использовать Single<TSource>(IEnumerable<TSource>) для выбора единственного элемента массива.

string[] fruits1 = { "orange" };

string fruit1 = fruits1.Single();

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.
Dim result As String = fruits1.Single()

' Display the result.
Console.WriteLine($"First query: {result}")

В следующем примере кода показано, что Single<TSource>(IEnumerable<TSource>) вызывает исключение, если последовательность не содержит ровно одного элемента.

string[] fruits2 = { "orange", "apple" };
string fruit2 = null;

try
{
    fruit2 = fruits2.Single();
}
catch (System.InvalidOperationException)
{
    Console.WriteLine("The collection does not contain exactly one element.");
}

Console.WriteLine(fruit2);

/*
 This code produces the following output:

 The collection does not contain exactly one element.
*/
' Create an array that contains two items.
Dim fruits2() As String = {"orange", "apple"}

result = String.Empty

' Try to get the 'single' item in the array.
Try
    result = fruits2.Single()
Catch ex As System.InvalidOperationException
    result = "The collection does not contain exactly one element."
End Try

' Display the result.
Console.WriteLine($"Second query: {result}")

' This code produces the following output:
'
' First query: orange
' Second query: The collection does not contain exactly one element.

Комментарии

Метод Single<TSource>(IEnumerable<TSource>) создает исключение, если входная последовательность пуста. Чтобы вместо этого возвращать null , если входная последовательность пуста, используйте SingleOrDefault.

Применяется к