IEnumerable with C#

Introduction:
IEnumerable. A List, array, and query can be looped over. This makes sense. All these constructs implement methods from IEnumerable.

This article explains about the IEnumerable interface. We will discuss how IEnumerable interface facilitate the use of foreach statement to iterate through a set of data. We will then look how to implement our own collections that implement IEnumerable interface. The use of yield keyword and Enumerating generic collections will also be discussed in this article.

An interface, IEnumerable specifies that the underlying type implements GetEnumerator. It enables foreach. On IEnumerable things, extensions from System.Linq are often applied.

An IEnumerable generic interface is returned from query expressions. A query expression that selects ints will be of type IEnumerable<int>.

Foreach: On an IEnumerable variable, we can also use the foreach-loop. This loop iterates with simple syntax.
We can apply many transformations to an IEnumerable instance, including the ToList and ToArray conversions.

Example:-

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

Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment