Parsing CSV data into multidimensional array

G

Guest

Hi folks,

New C# programmer here.

I am reading some CSV data from a file into an ArrayList. I want to get the
data from the ArrayList into a 2-dimensional array. I see a few references to
..Split, but I'm not sure that's what I need.

So, basically, what I have loaded into the ArrayList is:

"a, 1"
"b, 2"
"c, 3"

And what I want is a 2-d array with

array[0,0] == "a"
array[0,1] == "1"
array[1,0] == "b" etc.

Here's my code so far:

static void Main(string[] args)
{
//open streamreader to read in data file
StreamReader objReader = new StreamReader("c:\\data.csv");
string sLine="";

//read file in as an arraylist
ArrayList arrText = new ArrayList();

//read until end of file
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
//add each line of text file in
arrText.Add(sLine);
}
objReader.Close();

//create the 2-d array
string [ , ] mydata;

//parse out the columns
//mystery code goes here


You guys are great. Thanks in advance for any help/advice.

Dave
 
W

William Stacey [MVP]

Here is one way I would do it. I use an ArrayList as I don't know before
hand how many lines I will parse:

private void button9_Click(object sender, System.EventArgs e)
{
// Split line on commas followed by zero or more spaces.
Regex splitRx = new Regex(@",\s*", RegexOptions.Compiled);
ArrayList al = new ArrayList();
using(StreamReader sr = new StreamReader(@"c:\mycsv.csv"))
{
string line = null;
int ln = 0;
while((line = sr.ReadLine()) != null)
{
string[] fields = splitRx.Split(line);
if ( fields.Length != 2 )
{
Console.WriteLine("Invalid Input on line:"+ln);
continue;
}
ln++;
al.Add(fields);
}
}

Console.WriteLine("\nI processed {0} lines:", al.Count);
foreach(string[] sa in al)
{
Console.WriteLine("[{0}] [{1}]", sa[0], sa[1]);
}
}

------- mycsv.csv File ---------
a,1
b,2
c, 3
d, 4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top