Reputation: 39437
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?
Upvotes: 55
Views: 102881
Reputation: 2210
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();
Upvotes: 3
Reputation: 24754
using System.Linq;
Use the .ToList() method. Found in the System.Linq namespace.
var yourList = yourEnumerable.ToList();
https://learn.microsoft.com/en-us/dotnet/api/system.linq?view=netcore-2.2
Upvotes: 53
Reputation: 25401
As others suggested, simply use the ToList()
method on an enumerable object:
var myList = myEnumerable.ToList()
But, if your object implementing the IEnumerable
interface doesn't have the ToList()
method and you're getting an error like the following:
'IEnumerable' does not contain a definition for 'ToList'
...you're probably missing the System.Linq
namespace, because the ToList()
method is an extension method provided by that namespace, it's not a member of the IEnumerable
interface itself.
So just add the namespace to your source file:
using System.Linq
Upvotes: 7
Reputation: 2476
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);
}
Upvotes: 67
Reputation: 104721
Create a new List and pass the old IEnumerable to its initializer:
IEnumerable<int> enumerable = GetIEnumerable<T>();
List<int> list = new List<int>(enumerable);
Upvotes: 3
Reputation: 50712
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>;
Upvotes: 0