Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from IEnumerable to List [duplicate]

I want to convert from IEnumerable<Contact> to List<Contact>. How can I do this?

like image 390
kartal Avatar asked Oct 01 '11 02:10

kartal


People also ask

Can we convert 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();

Is List faster than IEnumerable?

Is IEnumerable faster than List? IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.

What is the difference between IEnumerable and List?

IEnumerable types have a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out. List implements IEnumerable, but represents the entire collection in memory.


2 Answers

You can do this very simply using LINQ.

Make sure this using is at the top of your C# file:

using System.Linq; 

Then use the ToList extension method.

Example:

IEnumerable<int> enumerable = Enumerable.Range(1, 300); List<int> asList = enumerable.ToList(); 
like image 138
vcsjones Avatar answered Oct 02 '22 18:10

vcsjones


In case you're working with a regular old System.Collections.IEnumerable instead of IEnumerable<T> you can use enumerable.Cast<object>().ToList()

like image 38
cordialgerm Avatar answered Oct 02 '22 18:10

cordialgerm