Home
Map
AsEnumerable MethodUse the AsEnumerable extension method from System.Linq to cast to IEnumerable.
C#
This page was last reviewed on Sep 26, 2022.
AsEnumerable. The IEnumerable interface defines a template that types can implement for looping. AsEnumerable is a generic method that converts its argument to IEnumerable.
IEnumerable
Casting info. 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.
Example. 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.
int Array
Extension
Next The example code also shows the implementation of 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 6
public static IEnumerable<TSource> AsEnumerable<TSource>( this IEnumerable<TSource> source) { return source; }
Output notes. You can see that the value returned by the AsEnumerable method invocation is typed with the implicit type var. This makes the syntax clearer.
var
Info You could explicitly specify the type as IEnumerable int instead. This would be harder to read.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.