Note that there are some explanatory texts on larger screens.

plurals
  1. POSplit array into size limited CSV strings
    primarykey
    data
    text
    <p>I am looking for an efficient way to convert a large int[] into a string[] of csv strings where each csv is limited to a maximum of 4000 characters. The values in the array could be anything between 1 and int.MaxValue.</p> <p>Here is my final code:</p> <pre><code>public static string[] GetCSVsFromArray(int[] array, int csvLimit) { List&lt;string&gt; parts = new List&lt;string&gt;(); StringBuilder sb = new StringBuilder(); foreach(int id in array) { string intId = id.ToString(); if (sb.Length + intId.Length &lt; csvLimit) sb.Append(intId).Append(","); else { if (sb.Length &gt; 0) sb.Length--; parts.Add(sb.ToString()); sb.Length = 0; } } if(sb.Length&gt;0) parts.Add(sb.ToString()); return parts.ToArray(); } </code></pre> <p>Is there a more efficient way to do this?</p> <p>So here is what I am now using (I was able to change the return parameter to the List type to save the ToArray() call at the end):</p> <pre><code>public static List&lt;string&gt; GetCSVsFromArray(int[] array, int csvLimit) { List&lt;string&gt; parts = new List&lt;string&gt;(); StringBuilder sb = new StringBuilder(); foreach(int id in array) { string intId = id.ToString(); if (sb.Length + intId.Length &lt; csvLimit) sb.Append(intId).Append(","); else { if (sb.Length &gt; 0) sb.Length--; parts.Add(sb.ToString()); sb.Length = 0; } } if(sb.Length&gt;0) parts.Add(sb.ToString()); return parts; } </code></pre> <p>Performance results:</p> <p>10,000,000 items csv Limit of 4000 characters</p> <ul> <li>Original: 2,887.488ms</li> <li>GetIntegerDigitCount: 3105.355ms</li> <li>Final: 2883.587ms</li> </ul> <p>Whilst I only saved 4ms removing the ToArray() call on my developer machine this seems to make a significant difference on a much slower machine (saved over 200ms on a DELL D620)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload