C# Convert IEnumerable to List

Posted: 2009-12-02 in Code and Computers

Problem: using yield return returns an IEnumerable. To use it though you will need something like this IList<T>

In 3.0 + this is easy, import namespace:

using System.Linq;

and you will now have access to .ToList() on anything IEnumerable

If you don’t have 3.0 or newer then you can do something like the following:

private static IList<T> EnumerableToList<T>(IEnumerable<T> castMePlease)
IList<T> list = new List<T>();
foreach (T enumerable in castMePlease)
return list;
Also many thanks to Fredrik Mörk for pointing out a slight error on old school vs new school, his excellent blog can be found here..

  1. Fredrik says:

    But, what’s wrong with the LINQ extension methods? There is already a .ToList() method, as well as the mighty powerful .Where and .Select extension methods. Or are you restricted to 2.0 code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s