假设我有这个数组
[0,0] = A
[0,1] = B
[0,2] = C
[1,0] = D
[1,1] = E
[1,2] = F
[2,0] = G
[2,1] = H
[2,2] = I
[3,0] = J
[3,1] = K
[3,2] = L
我希望它们能被写入一个文本文件,格式如下:
A B C
D E F
G H I
J K L
我应该做什么?
假设我有这个数组
[0,0] = A
[0,1] = B
[0,2] = C
[1,0] = D
[1,1] = E
[1,2] = F
[2,0] = G
[2,1] = H
[2,2] = I
[3,0] = J
[3,1] = K
[3,2] = L
A B C
D E F
G H I
J K L
我应该做什么?
static void Main(string[] args)
{
var array = new string[4, 3];
array[0, 0] = "A";
array[0, 1] = "B";
array[0, 2] = "C";
array[1, 0] = "D";
array[1, 1] = "E";
array[1, 2] = "F";
array[2, 0] = "G";
array[2, 1] = "H";
array[2, 2] = "I";
array[3, 0] = "J";
array[3, 1] = "K";
array[3, 2] = "L";
using (var sw = new StreamWriter("outputText.txt"))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
sw.Write(array[i,j] + " ");
}
sw.Write("\n");
}
sw.Flush();
sw.Close();
}
}
锯齿形数组通常比二维数组更方便。
public static class ArrayExtensions {
// In order to convert any 2d array to jagged one
// let's use a generic implementation
public static T[][] ToJagged<T>(this T[,] value) {
if (Object.ReferenceEquals(null, value))
return null;
// Jagged array creation
T[][] result = new T[value.GetLength(0)][];
for (int i = 0; i < value.GetLength(0); ++i)
result[i] = new T[value.GetLength(1)];
// Jagged array filling
for (int i = 0; i < value.GetLength(0); ++i)
for (int j = 0; j < value.GetLength(1); ++j)
result[i][j] = value[i, j];
return result;
}
}
在您的情况下,您可以将 2D 数组转换为 嵌套数组 然后使用 Linq:
var array = new string[,] {
{"A", "B", "C"},
{"D", "E", "F"},
{"G", "H", "I"},
{"J", "K", "L"},
};
File.WriteAllLines(@"C:\MyFile.txt", array
.ToJagged()
.Select(line => String.Join(" ", line));