Manish Sinha
Manish Sinha

Reputation: 2112

.NET converting simple arrays to List Generics

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

Upvotes: 14

Views: 30261

Answers (5)

AnorZaken
AnorZaken

Reputation: 2124

Do you really need a List, or will an IList work for you? Because the CLR (has special code to) support casting of arrays to generic collection interfaces, simply:

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

Upvotes: 1

Fadrian Sudaman
Fadrian Sudaman

Reputation: 6465

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.

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

Upvotes: 30

doriath
doriath

Reputation: 96

object[] array = new object[10];
List<object> list = array.ToList();

Method ToList is linq method. You need to add

using System.Linq;

Upvotes: 4

AxelEckenberger
AxelEckenberger

Reputation: 16926

Use:

using System.Linq;

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

Upvotes: 4

user180326
user180326

Reputation:

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.

Upvotes: 10

Related Questions