Home > OS >  Visual C# Cannot get CSV file to load into a 2D array
Visual C# Cannot get CSV file to load into a 2D array

Time:11-05

I have a very simple .csv file with ID's and serial numbers the actual application will not know how many rows but will always have two columns

1,16600687 2,16600939 3,16604031 4,16607302

I have everything else setup but i am only loading the data into a 1D array and the comma is remaining in the data

The result i get is string value for 3rd position is 3,16604031 How do i separate this so it is a 2D array with get value [2,0] is 3 and get value [2,1] is 16604031 ?

private void button1_Click(object sender, EventArgs e)
     {
         string stFileNamenPath = "(put location of file here)";
         DialogResult result = openFileDialog1.ShowDialog(); 
         StreamReader sr = new StreamReader(stFileNamenPath);  
         string[] sortArray = null;
         while (!sr.EndOfStream)
         {
             string strResult = sr.ReadToEnd();
             sortArray = strResult.Split(new string[] { Environment.NewLine },   StringSplitOptions.None);
         }
         string stTest = (string)sortArray.GetValue(2);
         MessageBox.Show("string value for 3rd position is "   stTest);
     }

CSV file

1,16600687
2,16600939
3,16604031
4,16607302

CodePudding user response:

The answer that comes to my mind is just a LINQ Where statement followed by a Select statement. The former for filtering and the second for actually remaping the data you have. You code would be something like this

        string stFileNamenPath = "(put location of file here)";
        //DialogResult result = openFileDialog1.ShowDialog();
        StreamReader sr = new StreamReader(stFileNamenPath);
        string[] sortArray = null;
        while (!sr.EndOfStream)
        {
            string strResult = sr.ReadToEnd();
            sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        }
        char separator = ',';
        var mappedArray = sortArray
            .Where(x => !string.IsNullOrEmpty(x) && !string.IsNullOrWhiteSpace(x))
            .Select(x => new string[] { x.Split(separator)[0], x.Split(separator)[1] }).ToArray();

        var stTest = mappedArray[2][1];
        MessageBox.Show("string value for 3rd position is "   stTest);
  • Related