.NET converting simple arrays to List Generics

Posted by Manish Sinha on Stack Overflow See other posts from Stack Overflow or by Manish Sinha
Published on 2010-03-09T10:44:16Z Indexed on 2010/03/09 10:51 UTC
Read the original article Hit count: 642

Filed under:
|
|
|
|

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

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#