C# IEnumerable

Loop

The IEnumerable interface appears throughout C# programs. It specifies that the underlying type implements the GetEnumerator method. It enables the foreach-loop to be used. It often interacts with methods from the System.Linq namespace.

Foreach

Example

Generic

An IEnumerable generic interface is returned from query expressions. A query expression that selects ints will be of type IEnumerable<int>. On an IEnumerable variable, you can also use the foreach-loop.

Tip:You can apply lots of transformations to an IEnumerable instance, including the ToList and ToArray conversions.

ToListToArrayAverage
Based on:

.NET 4.5

C# program that uses IEnumerable

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

Method

Because many types implement IEnumerable, you can pass them directly to methods that receive IEnumerable arguments. The type parameter must be the same. The next method receives an IEnumerable argument. You can pass Lists or arrays to it.

ListArray

Also:You can implement IEnumerable on a type to provide support for the foreach-loop. This is done through the GetEnumerator method.

C# program that uses IEnumerable argument

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
True

Array

2D array

IEnumerable works with a 2D array. It enables a foreach-loop over the values in your 2D or jagged array. This results in fewer typo bugs and shorter code. We create a custom method that returns IEnumerable.

2D ArrayYield keyword

Foreach:We use IEnumerable and the foreach-loop to loop through all items in a 2D array. We can abstract the loop itself out.

Here:This example shows the yield contextual keyword in a method that returns IEnumerable<T>.

C# program that uses array, yield keyword

using System;
using System.Collections.Generic;

class Program
{
    static int[,] _grid = new int[15, 15];
    static void Main()
    {
	_grid[0, 1] = 4;
	_grid[4, 4] = 5;
	_grid[14, 2] = 3;
	int r = 0;
	foreach (int v in GridValues())
	{
	    r += v;
	}
	Console.WriteLine(r);
    }
    public static IEnumerable<int> GridValues()
    {
	for (int x = 0; x < 15; x++)
	{
	    for (int y = 0; y < 15; y++)
	    {
		yield return _grid[x, y];
	    }
	}
    }
}

Output

12
Squares

In this example, the return value is an IEnumerable collection of ints. Because it is a generic type, the type of the IEnumerable return value is in the angle braces. An IEnumerable collection is one we can loop over.

Generic ClassInt

Yield:The yield keyword is one you put before return. It is only used on enumerators, such as this one that returns IEnumerable.

Yield

State:We can use yield to "save the state" of the function after the return. This work is performed by the compiler.

Foreach

Foreach loop construct

One advantage with using foreach loops is that they eliminate your need to track indexer variables, such as "i" or "x". The code becomes safer and more robust by hiding all the details from the programmers using the array.

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

C#: Interface