user5468794 user5468794 - 11 months ago 45
C# Question

String array run through string until char then save to 2D array

I have a string array that contains an ID, Path, and File Name. They are all divided by a semicolon and it looks something like this:

1.235.554;C:\somewhere\somewhere\this is name of doc.txt;this is name of doc

My code is as follows:

//string array already has data
string[] file_final;

//gets height to find array size
int height = file_final.GetLength(0);

//declares 2d array
string[,] table = new string[height, 3];

for(int i = 0; i < height; i++){ //loops until height is hit
foreach(char c in file_final[i]) //checks each char in line[i]
if(c != ';'){ //if not ; then
string temp; //I would like to save each char into this string
//temp = temp append/insert/+ didnt work
// I know data conversion from char to string is an issue


My desired output would be:

[0,0] = 1.235.554 (ID)

[0,1] = C:\somewhere\somewhere\this is name of doc.txt (Path)

[0,2] = this is name of doc (File name)

And so on and so forth until we run out of lines in the file to read.

I am having issues with char to string, which I know is two different data types but I thought append would work. Should I save each char until the semi colon in my temp string then add it to the array, clear my string, continue reading the rest of the line, increment my array index then save again until end of line?

Answer Source

If you are OK into storing the data in a string[][] instead of a string[,],

Use System.Linq

string[][] table = File.ReadAllLines(filePath)
                       .Select(line => line.Split(';'))

If you really need to have the data stored in a multi-dimensional array, you can use this extension method to convert your jagged array into a two-dimensional one:

public static TSource[,] To2D<TSource>(this TSource[][] jaggedArray)
    int firstDimension = jaggedArray.Length;
    int secondDimension = jaggedArray.GroupBy(row => row.Length).Single().Key;

    TSource[,] result = new TSource[firstDimension, secondDimension];
    for (int i = 0; i < firstDimension; ++i)
        for (int j = 0; j < secondDimension; ++j)
           result[i, j] = jaggedArray[i][j];

    return result;

You'd then have the following code:

string[,] table = File.ReadAllLines(filePath)
                      .Select(line => line.Split(';'))