views:

1995

answers:

5

Lists in c# have the .toArray() function. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but i would like a one liner to swap it back.

I am using the string.split function in the .NET 2.0 environment so Linq etc. is not available to me.

+5  A: 
return new List<string>(stringArray);
Ty
+12  A: 
string s = ...
new List<string>(s.Split(....));
Ovidiu Pacurar
You want to be careful here to use StringSplitOptions.RemoveEmptyEntries or you may end up with a list with a single empty string instead of a list with no elements when the string is the empty string. Probably not what you want.
tvanfosson
True, but it is the same without having the results in a List, so it depends on what he needs from the split function, and not how the data is stored.
Ovidiu Pacurar
Just wanted to mention it since there is a semantic difference between an empty List and a List with one empty element.
tvanfosson
+3  A: 

In .Net 3.5, the System.Linq namespace includes an extension method called ToList<>().

Max Lybbert
Thanks! Exactly what I needed.
David
A: 

If all you need is an object that implements the IList interface and you do not need to add new items you might also do it like this:

IList<string> list = myString.Split(' ');
Peter van der Heijden
A: 

But the point is to split the string to use for LINQ and the IList interface is no good for that. This will do the trick though there might be a more efficient way.

Andy