Question

Still learning and looking for a little guidance - I've got a CSV file that I'm reading into my program using a method with two foreach loops like so:

int i = 0;
int j = 0;
string File = File.ReadAllText("c:\\employees.txt");

string[,] filesArray = new string[File.ReadLines("c:\\employees.txt").Count(), 4]; 

foreach (string row in rawFile.Split('\n'))
{
    foreach (string col in row.Trim().Split(','))
    {
        filesArray[i, j] = col;
        j++;
    }
    j = 0;
    i++;
}
return filesArray;

All well and good and I can dumbly display the text fine but the format of the CSV file is

Z0003, EmployeeNameHere, 00001

and I want to do some math and other calculations based on the values in filesArray[2, 0] and so on but I'm trying to find what would be best practice for this situation.

I can think of ways that don't seem elegant and honestly it's been a bit of a mess trying to find the exact answer to this question through Google. I don't want to pick up bad habits at such an early stage!

Was it helpful?

Solution

Your problem right now is you have the data (even though getting it is ugly), but it is all in strings. No matter what you do, you will have to convert to a decimal or other numeric format to do math on it.

I would recommend using a library like FileHelpers to read your CSV data into an "employee" class first. This will give you strongly typed objects. See the 'Quick Start Delimited' entry on the left side. your class would look something like this:

[DelimitedRecord(",")]
public class Employee {
    // fields in same order as in the file
    public string EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public int    MyNumber { get; set; }
}

Suggestions for current code:

  1. What is rawFile ?? you get the lines using ReadAllLines()
  2. Follow .NET naming guidelines. var file = ... not var File =
  3. Don't use the same name as common .Net classes (e.g. File). Call it fileLines, etc
  4. Don't read the file twice to get the # of lines. use new string[fileLines.Count, 4]
  5. You can use LINQ and calls to split easier if you don't use a [,] multi-dimensional array.
  6. To convert between string and int, you will need int.Parse or int.TryParse
  7. Add error checking to make sure your lines are the correct length, etc

Some sample code:

var data = fileLines.Select(line => line.Split(','))
                    .Where(arr => arr.Length == 4) // should have 4 fields
                    .ToArray();

var xxxx = data[0][1]; // should be "EmployeeNameHere"

// this assumes your data is ALL valid
var numbers = data.Select(x => int.Parse(x[2])).ToList();
var sum = numbers.Sum();

// there is no "pretty" way to do TryParse
var numbers = new List<int>();
foreach(var arr in data) {
    int temp = 0;
    if (int.TryParse(arr[2], out temp)) { 
         numbers.Add(temp);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top