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?
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?
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);
}
using System.Linq;
Use the .ToList() method. Found in the System.Linq namespace.
var yourList = yourEnumerable.ToList();
https://docs.microsoft.com/en-us/dotnet/api/system.linq?view=netcore-2.2
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>;
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.
IEnumerable<MyDocument> docList = await _documentRepository.GetListAsync();
So...if you are doing this and it does NOT work
List<MyDocument> docList = await _documentRepository.GetListAsync().ToList();
You are actually calling ToList on the Task<IEnumerable>! Add parenthesis around your await call like this
List<MyDocument> docList = (await _documentRepository.GetListAsync()).ToList();