简体   繁体   English

什么是分段数据最快的方法

[英]What is the fastest way to section data

I am not sure what this is called so Ill explain by giving an example. 我不确定这叫什么,所以我举个例子来解释。 I have an array of numbers 我有一个数字数组

76425
234786234
56
4356
564356
456
94
900
725

Now I would like to join this data and make a new array that looks like this 现在我想加入这些数据,并创建一个新的数组,看起来像这样

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

This is a string array that contains 3 items. 这是一个包含3个项目的字符串数组。 Items per row is 4. As you can see the last row only has one item. 每行的项目数为4。如您所见,最后一行只有一个项目。 That is ok. 那没问题。 Here is the code I have written to do this: 这是我为此编写的代码:

 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));
 }

This code works just fine. 这段代码可以正常工作。 But it is very slow. 但这很慢。 Do you have any ideas to make it faster. 您有什么想法可以使其更快。

Are you looking for something like this? 您是否正在寻找这样的东西?

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(',');
}

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]));
                   }
                }
            );

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM