对于单个代码行,您可以使用:
var temp = new string[,] { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8", "9" } };
var result = string.Join("\r\n\r\n",
temp.OfType<string>()
.Select((str, idx) => new {index = idx, value = str})
.GroupBy(a => a.index/(temp.GetUpperBound(0) + 1))
.Select(gr => gr.Select(n => n.value).ToArray())
.Select(a => string.Join("", a.SelectMany(x => x)))
.ToArray());
如果你不将数组定义为多维数组,单行代码看起来会好很多:
string[][] array2d = { new[] { "1", "2", "3" }, new[] { "4", "5", "6" }, new[] { "7", "8", "9" } };
string[][] jagged2d = { new[] { "1", "2", "3" }, new[] { "4", "5" }, new[] { "6" } };
string array2dConcatenate = string.Join("\r\n\r\n", array2d.Select(a => string.Join("", a.SelectMany(x => x))));
string jagged2dConcatenate = string.Join("\r\n\r\n", jagged2d.Select(a => string.Join("", a.SelectMany(x => x))));
只连接一个可以使用的多维数组:
string[,] multidimensional2d = { { "1", "2", "3" }, { "4", "5", "6" } };
string[,,] multidimensional3d = { { { "1", "2" }, { "3", "4" } }, { { "5", "6" }, { null, null } } };
string multidimensional2dConcatenate = string.Join(", ", multidimensional2d.OfType<string>());
string multidimensional3dConcatenate = string.Join(", ", multidimensional3d.OfType<string>());
要充分利用 linq,请参阅:When to use Cast() and Oftype() in Linq
如果您想使用 3d 数组或保护 null,您可以执行以下操作:
string[][][] array3d = { new[] { new[] { "1", "2" } }, new[] { new[] { "3", "4" } }, new[] { new[] { "5", "6" } }, null };
string[][][] jagged3d = { new[] { new[] { "1", "2" }, new[] { "3" } }, new[] { new[] { "4" }, new[] { "5" } }, new[] { new[] { "6" }, null }, null };
string array3dConcatenate = string.Join("\r\n\r\n", array3d.Where(x => x != null).SelectMany(x => x).Where(x => x != null).Select(a => string.Join("", a.SelectMany(x => x))));
string jagged3dConcatenate = string.Join("\r\n\r\n", jagged3d.Where(x => x != null).SelectMany(x => x).Where(x => x != null).Select(a => string.Join("", a.SelectMany(x => x))));