
Example

Foreach
Tip:
You can apply lots of transformations
to an IEnumerable instance, including the ToList and ToArray conversions.
ToList
ToArray
AverageProgram that uses IEnumerable [C#] using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { IEnumerable<int> result = from value in Enumerable.Range(0, 2) select value; // Loop. foreach (int value in result) { Console.WriteLine(value); } // We can use extension methods on IEnumerable<int> double average = result.Average(); // Extension methods can convert IEnumerable<int> List<int> list = result.ToList(); int[] array = result.ToArray(); } } Output 0 1
Example 2

List Array
Program that uses IEnumerable argument [C#] using System; using System.Collections.Generic; class Program { static void Main() { Display(new List<bool> { true, false, true }); } static void Display(IEnumerable<bool> argument) { foreach (bool value in argument) Console.WriteLine(value); } } Output True False TrueAlso, you can implement IEnumerable on a type to provide support for the foreach-loop. This is done through the GetEnumerator method. This is currently outside the scope of this article.
Summary
The IEnumerable<T> interface is a generic interface that provides an abstraction for looping over elements. In addition to providing foreach support, it allows you to use extension methods in the System.Linq namespace.Extension Method
0 comments:
Post a Comment