Casting IEnumerable<T> to List<T>

Viewed 89778

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?

6 Answers

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);
}

Create a new List and pass the old IEnumerable to its initializer:

    IEnumerable<int> enumerable = GetIEnumerable<T>();
    List<int> list = new List<int>(enumerable);

no, you should copy, if you are sure that the reference is reference to list, you can convert like this

List<int> intsList = enumIntList as List<int>;

Another gotcha (async call)

An async call may be your problem. If you added the using System.Linq statement and you are still getting the error "does not contain a definition for 'ToList' and no accessible extension method...", look carefully for the Task keyword in your error message.

Original Call (works)

IEnumerable<MyDocument> docList = await _documentRepository.GetListAsync();

Attempt to use ToList (still not working)

So...if you are doing this and it does NOT work

List<MyDocument> docList = await _documentRepository.GetListAsync().ToList();

Use parenthesis

You are actually calling ToList on the Task<IEnumerable>! Add parenthesis around your await call like this

List<MyDocument> docList = (await _documentRepository.GetListAsync()).ToList();
Related