我有一个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单元包含多个数组元素。如何解决?
答案 0 :(得分:2)
我会把循环写成像这样的东西:
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();
}
请注意,当您使用my2darray.GetLength(x)时,您的数组的类型为arr [,]而不是arr [] []。
另请注意,如果您希望在csv文件中转换矩阵,则必须更改i和y:my2darray [j,i]
锯齿状的版本可能是这样的(期望j维度i等于通过外部数组(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();
}
答案 1 :(得分:1)
我更愿意将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));
答案 2 :(得分:0)
有效。您可能没有使用正确的分隔符。试试&#34; \ r \ n&#34;换行并使用你的csv分隔符,例如&#34;,&#34;
答案 3 :(得分:0)
我得到了一个解决方案,如@ 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");
}