2

I have a a C# array from which I would like to get each element and store it in each csv cell.I have written the following:

StreamWriter file = new StreamWriter("C:/mylocation/data.csv");
//my2darray  is my 2d array created.
for (int i = 0; i < my2darray.GetLength(1); i++)
   {
            for (int j=0; j<my2darray.GetLength(0);j++)
            {
                file.Write(my2darray[i][j]);
                file.Write("\t");
            }
            file.Write("\n"); // go to next line
     }

The problem is that each csv cell contains more than one array element. How can it be fixed?

7
  • 3
    Does the application you're using to view the file accept tabs as delimiters? Typically a CSV file uses commas. (It is, after all, "Comma Separated Value.") Additionally, if you're on Windows, you'll probably want \r\n (Windows line ending) rather than just \n. To do line endings properly regardless of platform, you can use Environment.NewLine. Commented Sep 30, 2016 at 13:06
  • Since you are using j to iterate the second dimension of the array, shouldn't it be my2darray.GetLength(1) in the for statement? Commented Sep 30, 2016 at 13:12
  • Also, what type is my2darray? Is this an array of strings? If so, make sure you're putting quotes around the strings if they could contain your delimiter, and then make sure you're properly escaping any quotes they contain. Commented Sep 30, 2016 at 13:13
  • If you are using Excel to view the result, you can explicit chose the delimiter in the import wizard. Commented Sep 30, 2016 at 13:13
  • Also, is my2darray a rectangular array? That's what's implied by using GetLength(0) and GetLength(1), but then you access its contents like it's a jagged array (my2darray[i][j] rather than my2darray[i,j]). Also, I agree with @Kevin that it looks like you're not being consistent about the order of your array indexers. Commented Sep 30, 2016 at 13:16

4 Answers 4

2

I'd rather had separated CSV representing and saving:

private static IEnumerable<String> ToCsv<T>(T[,] data, string separator = ",") {
  for (int i = 0; i < data.GetLength(0); ++i)
    yield return string.Join(separator, Enumerable
      .Range(0, data.GetLength(1))
      .Select(j => data[i, j])); // simplest, we don't expect ',' and '"' in the items
}

...

File.WriteAllLines(@"C:/mylocation/data.csv",
  ToCsv(my2array));  
Sign up to request clarification or add additional context in comments.

Comments

2

I would write the loop as shomething like this:

  var my2darray = new[,]
  {
    { true, false, false, true },
    { true, false, false, true },
    { true, false, false, true },
    { true, false, false, true },
    { true, false, false, true },
  };

  var iLength = my2darray.GetLength(1);
  var jLength = my2darray.GetLength(0);

  for (int i = 0; i < iLength; i++)
  {
    for (int j = 0; j < jLength; j++)
    {
      file.Write("{0}\t", my2darray[j, i]);
    }
    file.WriteLine();
  }

Be aware that when you use my2darray.GetLength(x) then your array is of type arr[,] and not arr[][].

Also notice that if you want the matrix transposed in the csv-file you'll have to change i and y: my2darray[j, i]

A jagged version could be something like this (anticipating that the j-dimension i equal throughaout the outer array (i-dimension):

  var my2darray = new[]
  {
    new [] { true, false, false, true },
    new [] { true, false, false, true },
    new [] { true, false, false, true },
    new [] { true, false, false, true },
    new [] { true, false, false, true },
  };

  var iLength = my2darray.Length;
  var jLength = my2darray[0].Length;

  for (int j = 0; j < jLength; j++)
  {
    for (int i = 0; i < iLength; i++)
    {
      Console.Write("{0}\t", my2darray[i][j]);
    }
    Console.WriteLine();
  }

Comments

0

It works. You are probably not using the right delimiters. Try "\r\n" for newline and use your csv delimiter such as ","

Comments

-1

I have got a solution with the following slight modification as hinted by @adv12

StreamWriter file = new StreamWriter("C:/mylocation/data.csv");
//my2darray  is my 2d array created.
for (int i = 0; i < my2darray.GetLength(1); i++)
  {
        for (int j=0; j<my2darray.GetLength(0);j++)
        {  
            file.Write(my2darray[i,j]);

            //it is comman and not a tab
            file.Write(",");  
        }
        //go to next line
        file.Write("\n"); 

 }

1 Comment

Since StreamWriter implements IDisposable (and thus allocates resources) wrap it into using: using (StreamWriter file = new StreamWriter("C:/mylocation/data.csv") {... /* your code here*/...}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.