我有一个c#数组,我想从中获得每个元素并将其存储在每个csv单元格中。我写了以下内容:
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
}
问题是每个csv单元格包含多个数组元素。怎样才能解决这个问题?
我宁愿将CSV表示和保存分开:
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));
我会像这样写这个循环:
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();
}
请注意,当你使用my2array . getlength (x)时,你的数组类型是arr[,]而不是arr[][]。
还需要注意的是,如果你想在csv文件中调换矩阵,你必须改变i和y: my2array [j, i]
锯齿形的版本可能是这样的(预计第j维i在整个外部数组(第i维)中相等):
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();
}
可以。您可能没有使用正确的分隔符。尝试使用"rn"作为换行符,并使用csv分隔符,如","
我得到了一个解决方案,根据@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");
}