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?
In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();
IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.
What is IEnumerable in C#? IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
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://learn.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With