/// <summary> /// Writes all rows in <paramref name="this"/> to <paramref name="csvWriter"/>. /// </summary> /// <remarks> /// </remarks> /// <param name="this"> /// The <see cref="DataTable"/>. /// </param> /// <param name="csvWriter"> /// The <see cref="CsvWriter"/>. /// </param> /// <param name="writeHeaderRecord"> /// If <see langword="true"/>, a header record will also be written, which will be comprised of the column names defined for <paramref name="this"/>. /// </param> /// <param name="maximumRows"> /// The maximum number of rows from <paramref name="this"/> that should be written to <paramref name="csvWriter"/>. /// </param> /// <param name="objectToStringConverter"> /// Provides a means of converting values in the <see cref="DataRow"/>s to <see cref="String"/>s. /// </param> /// <returns> /// The actual number of rows from <paramref name="this"/> written to <paramref name="csvWriter"/>. /// </returns> public static int WriteCsv(this DataTable @this, CsvWriter csvWriter, bool writeHeaderRecord, int? maximumRows, Func<object, string> objectToStringConverter) { @this.AssertNotNull("@this"); csvWriter.AssertNotNull("csvWriter"); objectToStringConverter.AssertNotNull("objectToStringConverter"); var num = 0; if (writeHeaderRecord) { var columnNames = new string[@this.Columns.Count]; for (var i = 0; i < columnNames.Length; ++i) { columnNames[i] = @this.Columns[i].ColumnName; } csvWriter.WriteRecord(columnNames); } var maximum = maximumRows.GetValueOrDefault(int.MaxValue); var buffer = new DataRecord[16]; var bufferOffset = 0; foreach (DataRow row in @this.Rows) { var record = new DataRecord(); for (var i = 0; i < row.ItemArray.Length; ++i) { record.Add(objectToStringConverter(row.ItemArray[i])); } buffer[bufferOffset++] = record; if (bufferOffset == buffer.Length) { // buffer full csvWriter.WriteRecords(buffer, 0, buffer.Length); bufferOffset = 0; } if (++num == maximum) { break; } } // write any outstanding data in buffer csvWriter.WriteRecords(buffer, 0, bufferOffset); return num; }