Enumerable.SingleOrDefault Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает один, конкретный элемент последовательности или значение по умолчанию, если этот элемент не найден.
Перегрузки
| Имя | Описание |
|---|---|
| SingleOrDefault<TSource>(IEnumerable<TSource>) |
Возвращает единственный элемент последовательности или значение по умолчанию, если последовательность пуста; этот метод создает исключение, если в последовательности существует несколько элементов. |
| SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Возвращает единственный элемент последовательности, удовлетворяющий указанному условию или значению по умолчанию, если такой элемент не существует; Этот метод создает исключение, если несколько элементов удовлетворяют условию. |
SingleOrDefault<TSource>(IEnumerable<TSource>)
Возвращает единственный элемент последовательности или значение по умолчанию, если последовательность пуста; этот метод создает исключение, если в последовательности существует несколько элементов.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource SingleOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source);
public static TSource SingleOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source);
static member SingleOrDefault : seq<'Source> -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IEnumerable(Of TSource)) As TSource
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IEnumerable<TSource>
Значение, IEnumerable<T> возвращаемое одним элементом.
Возвращаемое значение
Один элемент входной последовательности или default(TSource), если последовательность не содержит элементов.
Исключения
source равно null.
Входная последовательность содержит несколько элементов.
Примеры
В следующем примере кода показано, как выбрать SingleOrDefault<TSource>(IEnumerable<TSource>) единственный элемент массива.
string[] fruits1 = { "orange" };
string fruit1 = fruits1.SingleOrDefault();
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 or else a default value.
Dim result As String = fruits1.SingleOrDefault()
' Display the result.
Console.WriteLine($"First array: {result}")
В следующем примере кода показано, что SingleOrDefault<TSource>(IEnumerable<TSource>) возвращает значение по умолчанию, если последовательность пуста.
string[] fruits2 = { };
string fruit2 = fruits2.SingleOrDefault();
Console.WriteLine(
String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);
/*
This code produces the following output:
No such string!
*/
' Create an empty array.
Dim fruits2() As String = {}
result = String.Empty
' Get the single item in the array or else a default value.
result = fruits2.SingleOrDefault()
' Display the result.
Dim output As String =
IIf(String.IsNullOrEmpty(result), "No single item found", result)
Console.WriteLine($"Second array: {output}")
' This code produces the following output:
'
' First array: orange
' Second array: No single item found
Иногда значение не является значением default(TSource) по умолчанию, которое требуется использовать, если коллекция не содержит элементов. Вместо проверки результата для нежелательного значения по умолчанию и изменения его при необходимости можно использовать DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) метод, чтобы указать значение по умолчанию, которое необходимо использовать, если коллекция пуста. Затем вызовите Single<TSource>(IEnumerable<TSource>), чтобы получить элемент. В следующем примере кода используются оба метода для получения значения по умолчанию 1, если коллекция номеров страниц пуста. Так как значение по умолчанию для целого числа равно 0, которое обычно не является допустимым номером страницы, значение по умолчанию должно быть указано как 1. Первая переменная результата проверяется на нежелательное значение по умолчанию после завершения выполнения запроса. Вторая переменная результата получается с помощью DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) указания значения по умолчанию 1.
int[] pageNumbers = { };
// Setting the default value to 1 after the query.
int pageNumber1 = pageNumbers.SingleOrDefault();
if (pageNumber1 == 0)
{
pageNumber1 = 1;
}
Console.WriteLine("The value of the pageNumber1 variable is {0}", pageNumber1);
// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int pageNumber2 = pageNumbers.DefaultIfEmpty(1).Single();
Console.WriteLine("The value of the pageNumber2 variable is {0}", pageNumber2);
/*
This code produces the following output:
The value of the pageNumber1 variable is 1
The value of the pageNumber2 variable is 1
*/
Dim pageNumbers() As Integer = {}
' Setting the default value to 1 after the query.
Dim pageNumber1 As Integer = pageNumbers.SingleOrDefault()
If pageNumber1 = 0 Then
pageNumber1 = 1
End If
Console.WriteLine($"The value of the pageNumber1 variable is {pageNumber1}")
' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim pageNumber2 As Integer = pageNumbers.DefaultIfEmpty(1).Single()
Console.WriteLine($"The value of the pageNumber2 variable is {pageNumber2}")
' This code produces the following output:
' The value of the pageNumber1 variable is 1
' The value of the pageNumber2 variable is 1
Комментарии
Значением по умолчанию для ссылочных и типы, допускающие значение NULL, является null.
Метод SingleOrDefault не предоставляет способ указания значения по умолчанию. Если вы хотите указать значение по умолчанию, отличное default(TSource)от этого, используйте DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) метод, как описано в разделе "Пример".
Применяется к
SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)
Возвращает единственный элемент последовательности, удовлетворяющий указанному условию или значению по умолчанию, если такой элемент не существует; Этот метод создает исключение, если несколько элементов удовлетворяют условию.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static TSource SingleOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, bool> ^ predicate);
public static TSource SingleOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
static member SingleOrDefault : seq<'Source> * Func<'Source, bool> -> 'Source
<Extension()>
Public Function SingleOrDefault(Of TSource) (source As IEnumerable(Of TSource), predicate As Func(Of TSource, Boolean)) As TSource
Параметры типа
- TSource
Тип элементов source.
Параметры
- source
- IEnumerable<TSource>
Объект, IEnumerable<T> из который возвращается один элемент.
Возвращаемое значение
Один элемент входной последовательности, удовлетворяющий условию или default(TSource), если такой элемент не найден.
Исключения
source или predicate есть null.
Несколько элементов удовлетворяют условию в predicate.
Примеры
В следующем примере кода показано, как использовать SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) для выбора единственного элемента массива, удовлетворяющего условию.
string[] fruits = { "apple", "banana", "mango",
"orange", "passionfruit", "grape" };
string fruit1 = fruits.SingleOrDefault(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 > 10.
Dim fruit1 As String =
fruits.SingleOrDefault(Function(fruit) fruit.Length > 10)
' Display the result.
Console.WriteLine($"First array: {fruit1}")
В следующем примере кода показано, что возвращает значение по умолчанию, SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) если последовательность не содержит элементов, удовлетворяющих условию.
string fruit2 =
fruits.SingleOrDefault(fruit => fruit.Length > 15);
Console.WriteLine(
String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2);
/*
This code produces the following output:
No such string!
*/
' Get the single item in the array whose length is > 15.
Dim fruit2 As String =
fruits.SingleOrDefault(Function(fruit) fruit.Length > 15)
' Display the result.
Dim output As String =
IIf(String.IsNullOrEmpty(fruit2), "No single item found", fruit2)
Console.WriteLine($"Second array: {output}")
' This code produces the following output:
'
' First array: passionfruit
' Second array: No single item found
Комментарии
Значением по умолчанию для ссылочных и типы, допускающие значение NULL, является null.