views:

1575

answers:

6

I'd like to do something like this:

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String) = Foo.Split(","c)

Of course Foo.Split returns a one-dimensional array of String, not a generic List. Is there a way to do this without iterating through the array to turn it into a generic List?

A: 

If you use Linq, you can use the ToList() extension method

Dim strings As List<string> = string_variable.Split().ToList<string>();
IAmCodeMonkey
How exactly do you propose using Linq to query a comma-separated string?
Herb Caudill
He's not querying it. The ToList() extension method Code Monkey shows in his answer is just part of the class of functionality common known as "Linq" (and is used to support LINQ query, but you can use it for other things)
James Curran
+5  A: 

You can use the List's constructor.

String foo = "a,b,c,d,e";
List<String> boo = new List<String>(foo.Split(","));
Mats Fredriksson
Gave answer to @Bob King for answering in VB.NET - thanks.
Herb Caudill
Sorry mats! No hard feelings!
Bob King
+6  A: 

If you don't want to use LINQ, you can do:

Dim foo As String = "a,b,c,d,e"
Dim boo As New List(Of String)(foo.Split(","c))
Bob King
+6  A: 

Do you really need a List<T> or will IList<T> do? Because string[] already implements the latter... just another reason why it's worth programming to the interfaces where you can. (It could be that in this case you really can't, admittedly.)

Jon Skeet
You can use IList<T>, in fact you should (even though I forgot to in my answer's code example)
IAmCodeMonkey
I agree, although I am trying to get into this habbit.
Saif Khan
+1  A: 

The easiest method would probably be the AddRange method.

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String)

Boo.AddRange(Foo.Split(","c))
amcoder
Thanks - this works as well as the accepted answer but is slightly less compact.
Herb Caudill
That code works? It looks to me like it would throw a NullReferenceException.
Kyralessa
You're right. I forgot to create the Boo instance.
amcoder
A: 

Here is how I am doing it ... since the split is looking for an array of char I clip off the first value in my string.

var values = labels.Split(" "[0]).ToList<string>();
mattruma