The Enumerable Class – Range, Repeat and Empty

by Christian Fredh 3. oktober 2009 19:36

The Enumerable class was introduced in .NET 3.5 and lives in the System.Linq namespace and provides the LINQ extension methods. It also has three static methods that can be really useful, Range, Repeat and Empty that all returns a generic IEnumerable.

Range

The Range method provides a quick way of getting a sequence of integers in a specified range. Instead of writing something like this to get a collection of integers:

static IEnumerable GetSequence(int start, int count)
{
    List sequence = new List();
    for (int i = start; i < start + count; i++)
    {
        sequence.Add(i);
    }

    return sequence;
}

or:

static IEnumerable<int> GetSequence(int start, int count)
{
    for (int i = start; i < start + count; i++)
    {
        yield return i;
    }
}

and call the method with:

IEnumerable<int> sequence = GetSequence(1, 100);

you could just write:

IEnumerable<int> sequence = Enumerable.Range(1, 100);

Repeat

The Repeat method provides a quick way of getting a collection of one repeated value. Instead of writing something like this:

static IEnumerable<T> GetSequence<T>(T value, int count)
{
    for (int i = 0; i < count; i++)
    {
        yield return value;
    }
}

and call the method with:

IEnumerable<string> sequence = GetSequence<string>("My Repeat Value", 10);

you could just write:

IEnumerable<string> sequence = Enumerable.Repeat<string>("My Repeat Value", 10);

Empty

Ever wanted to get or return an empty collection? I know I have. Until I found this method I have used things like:

return new int[] {};

and:

return new List<int>();

or in some situations:

yield break;

Using yield break has a major drawback that it cannot be used in catch blocks as described by Eric Lippert.

But the Empty method provides a clear and descriptive way of getting an empty collection of any type. Just write:

return Enumerable.Empty<int>();

Tags: , ,

.NET | .NET 3.5 | LINQ

Comments

2009-10-04 11:30:45 #

Camilla

Bueno!! Gracias!

Camilla
Querétaro, Mexico

Camilla Mexico |

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Christian Fredh

Christian Fredh

A twenty six year old solutions architect and developer living in Stockholm, Sweden. I work as a SharePoint consultant at Avega Group with .NET and SharePoint development.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view. Use the information on this site at your own risk.

Copyright

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

© Copyright 2009, Christian Fredh.