Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IEnumerable to List<string> in .net 2.0

I need to convert IEnumerable to a List<string>. one of the way is to itearte through this and add each object to a list but this process is vary time consuming. Is there any other way to do this. Any help would be appreciated.

like image 284
user1685652 Avatar asked Oct 05 '12 13:10

user1685652


1 Answers

You can pass the enumerable directly into the constructor of a new List<string> instace:

List<string> list = new List<string>(yourEnumerable);

or you can use the AddRange method:

List<string> list = new List<string>();
list.AddRange(yourEnumerable);

This answer assumes that you in fact already have an IEnumerable<string>.
If this is not the case, your only option is a loop:

List<string> list = new List<string>();
foreach(object item in yourEnumerable)
    list.Add(item.ToString());

BTW: You are saying:

one of the way is to itearte through this and add each object to a list but this process is vary time consuming

You need to iterate the enumerable in any case. How else would you get all values? In the first two sample codes I gave you, the enumeration is performed inside the List<T> class, but it is still happening.

like image 122
Daniel Hilgarth Avatar answered Oct 06 '22 22:10

Daniel Hilgarth