Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting IEnumerable<T> to List<T>

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?

like image 550
RCIX Avatar asked Jun 07 '09 07:06

RCIX


People also ask

Can you cast IEnumerable to 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();

What's the difference between IEnumerable T and List t?

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.

How define IEnumerable in C#?

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.


3 Answers

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);
}
like image 94
dmnd Avatar answered Oct 13 '22 09:10

dmnd


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

like image 33
John Farrell Avatar answered Oct 13 '22 08:10

John Farrell


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
like image 24
David Ferenczy Rogožan Avatar answered Oct 13 '22 09:10

David Ferenczy Rogožan