Casting IEnumerable<T> to List<T>

RCIX picture RCIX · Jun 7, 2009 · Viewed 74.9k times · Source

I was wondering if it is possible to cast an IEnumerable to a List. Is there any way to do it other than copying out each item into a list?

Answer

dmnd picture dmnd · Jun 7, 2009

As already suggested, use yourEnumerable.ToList(). It enumerates through your IEnumerable, storing the contents in a new List. You aren't necessarily copying an existing list, as your IEnumerable may be generating the elements lazily.

This is exactly what the other answers are suggesting, but clearer. Here's the disassembly so you can be sure:

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    return new List<TSource>(source);
}