I want to convert from IEnumerable<Contact>
to List<Contact>
. How can I do this?
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 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.
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.
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();
In case you're working with a regular old System.Collections.IEnumerable
instead of IEnumerable<T>
you can use enumerable.Cast<object>().ToList()
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