2

我不确定这叫什么,所以我举个例子来解释。我有一个数字数组

76425
234786234
56
4356
564356
456
94
900
725

现在我想加入这些数据并制作一个看起来像这样的新数组

76425,234786234,56,4356
564356,456,94,900
725

这是一个包含 3 个项目的字符串数组。每行项目数为 4。如您所见,最后一行只有一个项目。那没问题。这是我为此编写的代码:

 numberOfColumns = numberOfColumns > lineCount ? lineCount : numberOfColumns;
 int newLineCount = Convert.ToInt32(Math.Ceiling((Convert.ToDouble(lineCount))/numberOfColumns));
 StringBuilder sb = new StringBuilder();

 for (int i = 0; i < newLineCount; i++)
 {
      var page = lines.Skip(numberOfColumns * i).Take(numberOfColumns).Select(xx => xx.Trim());
      sb.AppendLine(string.Join(",",page));
 }

这段代码工作得很好。但这很慢。你有什么想法让它更快。

4

3 回答 3

5

你在寻找这样的东西吗?

StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.Count; i++)
{
    sb.Append(lines[i]);
    if ((i % 4) == 3)
        sb.AppendLine();
    else
        sb.Append(',');
}
于 2012-11-11T23:41:33.593 回答
0

Reducing the number of iterations will increase performance.

List<string> result = new List<string>();

for (int i = 0; i < lines.Count; i+=4)
{
 result.Add(string.Format ("{0},{1},{2},{3}", lines[i], lines[i+1], lines[i+2], lines[i+3]));
}

Also, you could use parallel processing, if you have a multicore processor.

 var linesPerProcessor = (int)(((lines.Count/4) / Environment.ProcessorCount)*4);
 Parallel.For(0,Environment.ProcessorCount -1
            ) =>
                {
                   for (int i = (p * linesPerProcessor); i < (p+1)*linesPerProcessor; i+=4)
                   {
                          result.Add(string.Format ("{0},{1},{2},{3}", 
                                lines[i], lines[i+1], lines[i+2], lines[i+3]));
                   }
                }
            );
于 2012-11-11T23:52:40.023 回答
0

Use:

var arr = new[]
    {
        76425,
234786234,
56,
4356,
564356,
456,
94,
900,
725,
    };

var result =
    arr.Select((x, i) => new {x, i})
    .GroupBy(t => t.i / 4)
    .Select(t => string.Join(",", t.Select(v => v.x)));

Output:

76425,234786234,56,4356
564356,456,94,900
725
于 2012-11-11T23:54:48.863 回答