Casting IEnumerable<T> to List<T>
C#ListIenumerableC# Problem Overview
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?
C# Solutions
Solution 1 - C#
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);
}
Solution 2 - C#
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
Solution 3 - C#
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
Solution 4 - C#
Create a new List
IEnumerable<int> enumerable = GetIEnumerable<T>();
List<int> list = new List<int>(enumerable);
Solution 5 - C#
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>;
Solution 6 - C#
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
List<MyDocument> docList = (await _documentRepository.GetListAsync()).ToList();