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?
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
2009-06-07 07:12:06
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
2009-06-07 07:31:56
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
2009-06-07 08:22:27
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
2009-06-07 07:13:02
+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
2009-06-07 07:27:38