Casting IEnumerable<T> to List<T>
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
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