Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, couldn't you please advise me how to create a string 2 dimensional array and copy there the data from the csv file. This code is not creating string data[,] array and do not copy the data from the csv file in the loop.


What I have tried:

using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using lpsolve55;

namespace LpSolveExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 158;
            int m = 9;
            string[,] data = new string[n, m];
            string path = "D:\\NM1997.csv";
            StreamReader sr = new StreamReader(path);
            int i = 0, j = 0;
            string line; string temp;
            char delim = ';';
            string[] mass_t;
            while (((line) = sr.ReadLine()) != null)
            {
                mass_t = line.Split(';');
                while (j < mass_t.Length)
                {
                    temp = mass_t[j];
                    data[i, j] = (temp);//this does not work
                    j++;
                }
                i++;
            }
            for(int k=0;k>158; k++)
            {
                for(int l =0;l<9;l++)
                {
                    Console.Write(data[i, j]);
                    Console.WriteLine();

                }
            }
        }
    }
}
Posted
Updated 17-Nov-17 20:13pm
Comments
Richard MacCutchan 17-Nov-17 13:40pm    
You never reset j to zero.
BillWoodruff 17-Nov-17 22:45pm    
Put break-points in your code, single-step through it using F11 in Visual Studio. Observe any errors or unexpected behavior/values. Report what you find here.

1 solution

Instead of using a while for your inner loop, use a for:
C#
while (!sr.EndOfStream)
{
    line = sr.ReadLine();
    mass_t = line.Split(';');
    for (int i = 0; j < mass_t.Length; j++)
    {
        temp = mass_t[j];
        data[i, j] = temp;
    }
    i++;
}

Or better, use File.ReadAllLines to read them all into an array of strings, and use foreach on that array.

Even better than that though would be to use A Fast CSV Reader[^] which will handle quoted strings as well. It can be configured to use ";" instead of "," as the separator.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900