Enumerable.AsEnumerable<TSource>(IEnumerable<TSource>) Метод
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает входное значение, типизированное как IEnumerable<T>.
public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TSource> ^ AsEnumerable(System::Collections::Generic::IEnumerable<TSource> ^ source);
public static System.Collections.Generic.IEnumerable<TSource> AsEnumerable<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);
static member AsEnumerable : seq<'Source> -> seq<'Source>
<Extension()>
Public Function AsEnumerable(Of TSource) (source As IEnumerable(Of TSource)) As IEnumerable(Of TSource)
- TSource
Тип элементов source
.
- source
- IEnumerable<TSource>
Последовательность, которая приводится к типу IEnumerable<T>.
Входная последовательность, приведенная к типу IEnumerable<T>.
В следующем примере кода показано, как использовать AsEnumerable<TSource>(IEnumerable<TSource>) для скрытия пользовательского Where
метода типа, когда требуется реализация стандартного оператора запроса.
// Custom class.
class Clump<T> : List<T>
{
// Custom implementation of Where().
public IEnumerable<T> Where(Func<T, bool> predicate)
{
Console.WriteLine("In Clump's implementation of Where().");
return Enumerable.Where(this, predicate);
}
}
static void AsEnumerableEx1()
{
// Create a new Clump<T> object.
Clump<string> fruitClump =
new Clump<string> { "apple", "passionfruit", "banana",
"mango", "orange", "blueberry", "grape", "strawberry" };
// First call to Where():
// Call Clump's Where() method with a predicate.
IEnumerable<string> query1 =
fruitClump.Where(fruit => fruit.Contains("o"));
Console.WriteLine("query1 has been created.\n");
// Second call to Where():
// First call AsEnumerable() to hide Clump's Where() method and thereby
// force System.Linq.Enumerable's Where() method to be called.
IEnumerable<string> query2 =
fruitClump.AsEnumerable().Where(fruit => fruit.Contains("o"));
// Display the output.
Console.WriteLine("query2 has been created.");
}
// This code produces the following output:
//
// In Clump's implementation of Where().
// query1 has been created.
//
// query2 has been created.
Dim output As New System.Text.StringBuilder
' A custom class.
Class Clump(Of T)
Inherits List(Of T)
' Constructor.
Public Sub New(ByVal collection As IEnumerable(Of T))
MyBase.New(collection)
End Sub
' Custom implementation of Where().
Function Where(ByVal predicate As Func(Of T, Boolean)) As IEnumerable(Of T)
output.AppendLine("In Clump's implementation of Where().")
Return Enumerable.Where(Me, predicate)
End Function
End Class
Sub AsEnumerableEx1()
' Create a new Clump(Of T) object.
Dim fruitClump As New Clump(Of String)(New String() _
{"apple", "passionfruit", "banana",
"mango", "orange", "blueberry",
"grape", "strawberry"})
' First call to Where():
' Call Clump's Where() method with a predicate.
Dim query1 As IEnumerable(Of String) =
fruitClump.Where(Function(fruit) fruit.Contains("o"))
output.AppendLine("query1 has been created." & vbCrLf)
' Second call to Where():
' First call AsEnumerable() to hide Clump's Where() method and thereby
' force System.Linq.Enumerable's Where() method to be called.
Dim query2 As IEnumerable(Of String) =
fruitClump.AsEnumerable().Where(Function(fruit) fruit.Contains("o"))
output.AppendLine("query2 has been created.")
' Display the output.
Console.WriteLine(output.ToString())
End Sub
' This code produces the following output:
'
' In Clump's implementation of Where().
' query1 has been created.
'
' query2 has been created.
Метод AsEnumerable<TSource>(IEnumerable<TSource>) не оказывает никакого влияния, кроме как изменить тип времени компиляции source
с типа, реализующего IEnumerable<T> сам по IEnumerable<T> себе.
AsEnumerable<TSource>(IEnumerable<TSource>) может использоваться для выбора между реализациями запросов, если последовательность реализует IEnumerable<T> , но также имеет другой набор открытых методов запроса. Например, при использовании универсального классаTable
, который реализует IEnumerable<T> и имеет собственные методы, такие как Where
, Select
и SelectMany
, вызов Where
будет вызывать открытый Where
метод .Table
Тип Table
, представляющий таблицу базы данных, может иметь Where
метод , который принимает аргумент предиката в виде дерева выражений и преобразует дерево в SQL для удаленного выполнения. Если удаленное выполнение нежелательно, например из-за того, что предикат вызывает локальный метод, AsEnumerable метод можно использовать для скрытия пользовательских методов и вместо этого сделать стандартные операторы запросов доступными.
Продукт | Версии |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
Отзыв о .NET
.NET — это проект с открытым исходным кодом. Выберите ссылку, чтобы оставить отзыв: