Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freely convert between List<T> and IEnumerable<T>

How can I convert a List<MyObject> to an IEnumerable<MyObject> and then back again?

I want to do this in order to run a series of LINQ statements on the List, e. g. Sort()

like image 832
TK. Avatar asked Jan 23 '09 12:01

TK.


People also ask

How do I change a List to IEnumerable?

We can use the AsEnumerable() function of LINQ to convert a list to an IEnumerable in C#.

How do I cast a List in IEnumerable?

You can use the extension method AsEnumerable in Assembly System. Core and System. Linq namespace : List<Book> list = new List<Book>(); return list.

Is IEnumerable better than List?

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.


1 Answers

List<string> myList = new List<string>(); IEnumerable<string> myEnumerable = myList; List<string> listAgain = myEnumerable.ToList(); 
like image 182
Tamas Czinege Avatar answered Sep 24 '22 15:09

Tamas Czinege