Loading...
Bizznessia .NET

Bizznessia .NET

Programming Language

Understanding IEnumerable in C# and Its role in data structures

Published 2 months ago Viewed 32 times

What is IEnumerable?

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.

How IEnumerable Works

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.

Example: Using IEnumerable with a List

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);
        }
    }
}

IEnumerable in Different Data Structures

1. Arrays

Arrays in C# implement IEnumerable<T>, allowing iteration through elements easily.

int[] numbers = { 10, 20, 30 };
IEnumerable<int> enumerableNumbers = numbers;

2. Lists

Lists implement IEnumerable<T> and allow dynamic resizing while supporting iteration.

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
IEnumerable<string> enumerableNames = names;

3. Dictionaries

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}");
}

IEnumerable vs. Other Collection Interfaces

IEnumerable vs. ICollection

ICollection<T> extends IEnumerable<T> and includes additional functionalities like Add, Remove, and Count.

IEnumerable vs. IList

IList<T> allows index-based access and modification, while IEnumerable<T> is read-only and supports only iteration.

When to Use IEnumerable

  • When you need to iterate over a collection without modifying it.
  • When working with LINQ queries for deferred execution.
  • When handling large datasets efficiently by streaming data instead of loading it all at once.

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.

Bizznessia .NET
Bizznessia .NET

Bizznessia .NET

Programming Language

More from Bizznessia .NET

Related Articles

Follow @GoConnect for insights and stories on building profitable online businesses, and connect with fellow entrepreneurs in the GoConnect community.