Question

I have built a VB.Net class that will be used in VBA for reading text files. I've set it up so the user can specify what tables in the file he wants to return. What I have done is build a StringBuilder of the tables, then return it as a jagged array, but I can't quite get the conversion of the builder to array part right. I'd like the the first level to be split on "NewLine" and the second level to be split on ",".

Is this possible without having to use multiple arrays and\or loops?

Was it helpful?

Solution

This will create the jagged array:

Dim myArray = (From row In myStringBuilder.ToString().Split({vbCrLf}, StringSplitOptions.None)
               Select (From col In row.Split(","c)
                       Select col
                      ).ToArray()
              ).ToArray()

Explanation:

  • First, we convert the StringBuilder to a String: myStringBuilder.ToString()
  • Then we split on line breaks: Split({vbCrLf}, StringSplitOptions.None). Since a line break consists of two characters in Windows, we use the Split overload that accepts a string array (hence the braces).
  • Within the row we split the line on commas: Split(","c). The c specifies that this is a character instead of a string.
  • Finally, we convert this enumerable of enumerables into an array of arrays by applying ToArray to the outer as well as the inner LINQ expression.

OTHER TIPS

You could represent your jagged array using nested lists and generics. The outer (row) would be a generic list and the inner (col) could be a list of strings.

Other approaches could leverage XML or LINQ but would be less efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top