Back
Close

C# LINQ Background Topics

player_one
14.2K views

IEnumerable<T>

Why learn about generators and IEnumerable<T>?

LINQ methods are extension methods to the IEnumerable<T> interface. It is important to understand how IEnumerable<T> works to fully understand the more subtle details of how LINQ works.

Collections as IEnumerable<T>

A method returning an object that implements the IEnumerable<T> interface can be enumerated via a foreach block. For example:

private IEnumerable<int> GetInts()
{
    return new List<int> { 2, 4, 5, 7 };
}

Since List<T> implements IEnumerable<T>, you can iterate the return value from GetInts() like so:

// Will print:
// Value: 2
// Value: 4
// Value: 5
// Value: 7
foreach (int val in GetInts())
{
    Console.WriteLine($"Value: {val}");
}

NOTE: IEnumerable<T> is an implementation of the Iterator Pattern in C#.

Not all that surprising or impressive, is it? Well, let's take a look at generators next. That's where the true value of IEnumerable<T> lies.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants