Converting From IEnumerable To List


Answer :

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're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.



//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();





If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,



IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();


But if the IEnumerable is null, when you try to convert it to a List, you'll get
ArgumentNullException saying Value cannot be null.



IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();


enter image description here



Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable