Ranhot Ranhot - 1 year ago 144
Vb.net Question

Convert range of number in string to list of integer

I have a string


I need to have it converted to a fully populated range of numbers in an array as below:


Do you have any ideas how to convert it?

Answer Source

This code should do the trick (the procedure is described in the comments):

Dim s As String = "2-6,8,10-15,20-23" 'Your values
Dim values As New List(Of Integer)() 'Create an List of Integer values / numbers
For Each value As String In s.Split(","C) ' Go through each string between a comma
If value.Contains("-"C) Then 'If this string contains a hyphen
    Dim begin As Integer = Convert.ToInt32(value.Split("-"C)(0)) 'split it to get the beginning value (in the first case 2)
    Dim [end] As Integer = Convert.ToInt32(value.Split("-"C)(1)) ' and to get the ending value (in the first case 6)
    For i As Integer = begin To [end] 'Then fill the integer List with values
      values.Add(Convert.ToInt32(value)) 'If the text doesn't contain a hyphen, simply add the value to the integer List
End If
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download