AsEnumerable
The IEnumerable
interface
defines a template that types can implement for looping. AsEnumerable
is a generic method that converts its argument to IEnumerable
.
AsEnumerable
allows you to cast a specific type to its IEnumerable
equivalent. So this is a method that performs a cast on its argument and returns it.
We must include the System.Linq
namespace to access AsEnumerable
. When you have an IEnumerable
collection, you typically access it through queries or a foreach
-loop.
AsEnumerable
in the .NET Framework. This only casts the parameter and returns it.using System; using System.Linq; class Program { static void Main() { // Create an array type. int[] array = new int[2]; array[0] = 5; array[1] = 6; // Call AsEnumerable method. var query = array.AsEnumerable(); foreach (var element in query) { Console.WriteLine(element); } } }5 6public static IEnumerable<TSource> AsEnumerable<TSource>( this IEnumerable<TSource> source) { return source; }
You can see that the value returned by the AsEnumerable
method invocation is typed with the implicit type var
. This makes the syntax clearer.
IEnumerable
int
instead. This would be harder to read.IEnumerable
provides a contract that allows a typed collection to be looped over. To get an IEnumerable
from a List
or array, you can invoke the AsEnumerable
extension method.