Programming Language
In C#, IEnumerable<T>
is an interface that allows iteration over a collection of elements. It is a fundamental concept in LINQ and is widely used when working with data structures that support iteration.
The IEnumerable
interface is defined as:
public interface IEnumerable<T>
{
IEnumerator<T> GetEnumerator();
}
This means any collection that implements IEnumerable<T>
can be iterated over using a foreach
loop.
IEnumerable<T>
provides only forward iteration and does not support random access. It is particularly useful when working with large data sets, streaming data, or deferred execution in LINQ queries.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
Arrays in C# implement IEnumerable<T>
, allowing iteration through elements easily.
int[] numbers = { 10, 20, 30 };
IEnumerable<int> enumerableNumbers = numbers;
Lists implement IEnumerable<T>
and allow dynamic resizing while supporting iteration.
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
IEnumerable<string> enumerableNames = names;
Dictionaries implement IEnumerable<KeyValuePair<TKey, TValue>>
, enabling iteration over key-value pairs.
Dictionary<int, string> students = new Dictionary<int, string>
{
{ 1, "John" },
{ 2, "Emma" }
};
foreach (var student in students)
{
Console.WriteLine($"ID: {student.Key}, Name: {student.Value}");
}
ICollection<T>
extends IEnumerable<T>
and includes additional functionalities like Add
, Remove
, and Count
.
IList<T>
allows index-based access and modification, while IEnumerable<T>
is read-only and supports only iteration.
IEnumerable<T>
is a powerful and essential interface in C#, enabling iteration over various data structures. Understanding its usage helps in writing cleaner, more efficient code when working with collections and LINQ operations.
Related Articles
Understanding Multithreading in C#