IEnumerable<T>
Interface
Represents a strongly typed collection that can be enumerated.
Summary
The IEnumerable<T>
interface is the base interface for all generic collections in the .NET Framework. It is used to iterate over a collection, which is a collection of items that can be accessed by index or by iterating through the collection. The IEnumerable<T>
interface exposes the GetEnumerator
method, which returns an enumerator for the collection.
Interface Declaration
public interface IEnumerable<out T> : IEnumerable
Members
Methods
Name | Description |
---|---|
IEnumerator<T> GetEnumerator() |
Returns an enumerator that iterates through the collection. The enumerator for a generic collection is typed to the type of elements in the collection. |
Remarks
The IEnumerable<T>
interface is the generic counterpart to the non-generic IEnumerable
interface. Most of the collections in the .NET Framework implement IEnumerable<T>
. LINQ queries are also based on IEnumerable<T>
.
When you use a foreach
loop to iterate over a collection that implements IEnumerable<T>
, the compiler generates code that calls the GetEnumerator
method to obtain an enumerator, and then repeatedly calls the MoveNext
method on the enumerator to get the next element.
Examples
Iterating over a List
The following example demonstrates how to use a foreach
loop to iterate over a List<string>
, which implements IEnumerable<string>
.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
// Iterating using foreach loop
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
Using GetEnumerator directly
Although the foreach
loop is the most common way to use IEnumerable<T>
, you can also use the GetEnumerator
method directly.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
using (IEnumerator<int> enumerator = numbers.GetEnumerator())
{
while (enumerator.MoveNext())
{
int currentNumber = enumerator.Current;
Console.WriteLine(currentNumber);
}
}
}
}