C# LINQ Background Topics

player_one
123.5K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content