tags:

views:

599

answers:

4

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?

+4  A: 

Use the .ToList() extension method.

yourEnumerable.ToList();
jfar
A: 

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>;
ArsenMkrt
If you're *sure* that it's a reference to a list, you should use a direct cast so that it will throw an exception if you're wrong. Use "as" if you think it *might* be a List<T> but you're not sure, and neither are error conditions. Then test whether the result is null.
Jon Skeet
Maybe add an 'if (intsList == null) intsList = new List<int>(enumIntList);' if it *might* be a 'List<int>', already, but there are some cases where it is not.
jerryjvl
A: 

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

    IEnumerable<int> enumerable = GetIEnumerable<T>();
    List<int> list = new List<int>(enumerable);
Shimmy
it's copy the list too..
ArsenMkrt
there will anyway need to be a copy.
Shimmy
+3  A: 

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