Monday, February 21, 2011

Is there an equivalent to String.Split that returns a generic list?

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?

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

    Dim strings As List<string> = string_variable.Split().ToList<string>();
    
    Herb Caudill : How exactly do you propose using Linq to query a comma-separated string?
    James Curran : 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)
  • You can use the List's constructor.

    String foo = "a,b,c,d,e";
    List<String> boo = new List<String>(foo.Split(","));
    
    Herb Caudill : Gave answer to @Bob King for answering in VB.NET - thanks.
    Bob King : Sorry mats! No hard feelings!
  • 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))
    
  • 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.)

    IAmCodeMonkey : You can use IList, in fact you should (even though I forgot to in my answer's code example)
    Saif Khan : I agree, although I am trying to get into this habbit.
  • 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))
    
    Herb Caudill : Thanks - this works as well as the accepted answer but is slightly less compact.
    Kyralessa : That code works? It looks to me like it would throw a NullReferenceException.
    amcoder : You're right. I forgot to create the Boo instance.
  • 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>();
    

0 comments:

Post a Comment