我有二维数组
var temp = new string[,] { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8", "9" } };
提醒:
string[,] != string[][]
我想转换成...
123
456
789
在这种情况下如何快速转换?
我有二维数组
var temp = new string[,] { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8", "9" } };
提醒:
string[,] != string[][]
我想转换成...
123
456
789
在这种情况下如何快速转换?
对于单个代码行,您可以使用:
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,请参阅:何时在 Linq 中使用 Cast() 和 Oftype()
如果您想使用 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))));
private static string ObjectToString(IList<object> messages)
{
StringBuilder builder = new StringBuilder();
foreach (var item in messages)
{
if (builder.Length > 0)
builder.Append(" ");
if (item is IList<object>)
builder.Append(ObjectToString((IList<object>)item));
else
builder.Append(item);
}
return builder.ToString();
}
这是一种带有 2 个嵌套循环的方法:
var temp = new string[,]{{"1","2","3"},{"4","5","6"}};
var output = new string[temp.GetUpperBound(0)+1];
for (int i = 0; i<=temp.GetUpperBound(0); i++)
{
var sb = new StringBuilder(temp.GetUpperBound(1)+1);
for (int j = 0; j<=temp.GetUpperBound(1); j++)
sb.Append(temp[i,j]);
output[i] = sb.ToString();
}
如果您认为可以将 2-d 数组视为 1-d 并绕过 2 个循环,这里有一些技巧:如何将一行值从 2D 数组复制到 1D 数组中?,但是为了能够使用这些技巧,您需要 char 数组,而不是您所要求的字符串数组。