要正确执行此操作,我首先需要处理您的数据。你有一个排序的分数数组。您希望将其输出到列,其中数据在填充之前填充 down,通过输出流(控制台)强烈倾向于在写入之前写入 across下。
这意味着为了避免输出流中的回溯(缓慢而棘手),我们需要在将内存中的数据写入控制台之前对其进行处理:
double[] scores = ...; //sorted data in here
// now some constants
const int cols = 5;
const int colWidth = 5;
const int colSpace = 4;
const string Header = "Score";
//figure out how many rows we need
int remainder = scores.Length % cols;
int rows = scores.Length / cols + (remainder > 0?1:0);
//organize the data into a 2d structure that matches the output
// I chose an array of arrays rather than 2d array so I can pass individual
// arrays to format function later on.
var data = new string[rows][];
int i = 0; //score index
for (int c = 0;c < cols;c++)
{
for (int r = 0;r < rows && i < scores.Length; r++)
{
//make sure nested array exists and is pre-populated with empty strings (string.Format() will choke later if we leave these as nulls)
data[r] = data[r] ?? Enumerable.Repeat("", cols).ToArray();
//skip this cell if it's at the bottom row of a later column in an unbalanced array
if (remainder > 0 && r == rows - 1 && c >= remainder) continue;
data[r][c] = scores[i].ToString();
i++;
}
}
//write the header
var format = string.Join("", Enumerable.Repeat("{0,-" + (colWidth + colSpace) + "}", cols));
Console.WriteLine(format, Header);
Console.WriteLine(format, new string('-', colWidth));
//write the data
format = string.Join("", Enumerable.Range(0,cols).Select(i => string.Format("{{{0},-{1}}}{2}", i, colWidth, new string(' ',colSpace))).ToArray());
for (int i = 0; i < rows; i++)
Console.WriteLine(format, data[i]);
使用此示例数据运行代码:
double[] scores = { 97.05,96.52,93.16,92.44,91.05,90.66,90.59,19.1, 18.4, 16.8, 11.1, 13.8, 12.2, 7.9, 8.1, 11.0, 14.5, 16.6, 21.3, 16, 17.9};
scores = scores.OrderBy(s => s*-1).ToArray();
我得到这个结果:
分数 分数 分数 分数
----- ----- ----- ----- -----
97.05 90.66 18.4 16 11.1
96.52 90.59 17.9 14.5 11
93.16 21.3 16.8 13.8 8.1
92.44 19.1 16.6 12.2 7.9
91.05
这里很酷的是,这段代码可以让您轻松调整所需的列数。