views:

163

answers:

4

This question might seem trivial and also stupid at the first glance, but it is much more than this.

I have an array of any type T (T[]) and I want to convert it into a List generic (List<T>). Is there any other way apart from creating a Generic list, traversing the whole array and adding the element in the List?

Present Situation:

string[] strList = {"foo","bar","meh"};
List<string> listOfStr = new List<string>();
foreach(string s in strList)
{
    listOfStr.Add(s);
}

My ideal situation:

string[] strList = {"foo","bar","meh"};
List<string> listOfStr = strList.ToList<string>();

Or:

string[] strList = {"foo","bar","meh"};
List<string> listOfStr = new List<string>(strList);

I am suggesting the last 2 method names as I think compiler or CLR can perform some optimizations on the whole operations if It want inbuilt.

P.S.: I am not talking about the Array or ArrayList Type

+7  A: 

If you reference System.Linq, you can type:

string[] strList = {'foo','bar','meh'}; 
List<string> listOfStr = strList.ToList(); 

exactly like you want to.

The second syntax should also work.

jdv
+4  A: 

Use:

using System.Linq;

string[] strList = {'foo','bar','meh'};
List<string> listOfStr = strList.ToList();
Obalix
+3  A: 
object[] array = new object[10];
List<object> list = array.ToList();

Method ToList is linq method. You need to add

using System.Linq;
doriath
+7  A: 

If I understand your question correctly, one of the code segment you have will work. In C#, string needs to be enclosed in double quote, not single. You will need include System.Linq namespace

string[] strList = {"foo","bar","meh"};
List<string> listOfStr = new List<string>(strList);
Fadrian Sudaman
Yea, I do this all the time... well, sometimes.
Benny Jobigan
Sorry for the quote mistake. I Fixed it now.
Manish Sinha
This doesn't need LINQ and is the simplest technique.
Pratik
Pratik, without Linq - `new List<string>(strList)` is not allowed. It accepts only an instance of `IEnumerable<T>` (IIRC)
Manish Sinha
Array implements IEnumerable<T> since .NET 2.0
Programming Hero
Thanks Fadrian. It works like charm.
Manish Sinha