Reputation: 5
A bit stumped here. Attempting to Parse the numbers from a CSV file into two int variable arrays. However, it parses the first number only into both and not the second one.
Example of CSV file:
10000,46
10001,76
10002,100
string[] studentID = new string[STUDENT_TOTAL];
string[] studentMarks = new string[STUDENT_TOTAL];
studentID = line.Trim().Split(',');
studentMarks = line.Trim().Split(',');
int id = int.Parse(studentID[counter]);
int mark = int.Parse(studentMarks[counter]);
id should be 10000 and mark should be 46 for the first line. Any hints or full fixes. We are using Arrays only. No lists.
Upvotes: 0
Views: 223
Reputation: 117185
The issue is that you are only parsing the first value.
Your code effectively calls this:
int id = int.Parse(line.Trim().Split(',')[counter]);
int mark = int.Parse(line.Trim().Split(',')[counter]);
I assume that counter
is always 0
.
You could make it work like this:
int id = int.Parse(line.Trim().Split(',')[0]);
int mark = int.Parse(line.Trim().Split(',')[1]);
But I suggest you do a bit of refactoring and do it this way:
var results =
File
.ReadAllLines(@"path")
.Select(x => x.Trim().Split(','))
.Select(x => new { id = x[0], mark = x[1] })
.ToArray();
string[] studentID = results.Select(x => x.id).ToArray();
string[] studentMarks = results.Select(x => x.mark).ToArray();
Or even better, make a dictionary that will let you look-up the students marks:
Dictionary<int, int> lookup =
File
.ReadAllLines(@"path")
.Select(x => x.Trim().Split(','))
.Select(x => new { id = x[0], mark = x[1] })
.ToDictionary(x => x.id, x => x.mark);
Upvotes: 4
Reputation: 79
In addition to Steve's answer, you could try splitting the entire file into a line array. For example:
string[] Lines = CSVText.Split( Enviroment.Newline );
Then using a for loop to read each line/column value Or a foreach block.
for ( int line = 0; line < Lines.Length; line++ ) {
string[] linedata = line.Trim().Split(',');
studentID = linedata[0];
studentMarks = linedata[1]; }
And he is right, lists are quite good for that.
Upvotes: 1
Reputation: 9603
line.Trim().Split(',') returns a string array. So split the line first, then assign each index to the relevent variables.
var lineValues = line.Trim().Split(',');
studentID = lineValues[0];
studentMarks = lineValues[1];
You will need to do this for each line. Is there a reason you're not using lists? That will make it easier since you can just add each value for each iteration of the file.
Upvotes: 1