I have to get data from 2 tables and then merge them into a CSV file.
Table 1 has 50 columns, table 2 has 20 columns. I have 30k records in table 1 and 10k in table 2.
Code is working fine and takes 1 to 2 minutes for complete processing. Database query is quick it is just for each loop taking time due to number of rows.
Can this code be improved? It will be deployed in an azure function app and it will take lot more time then running locally on my computer.
Basically, I need to write all fields from Table 1 and then a "Comment" column at the end. Comment value come form a different table, so I perform a lookup in memory and find a row. If found, I write the value of the column otherwise I write empty.
My code is
var records = await ExecuteQuery(all_variations_query, tableName);
using var writer = new StreamWriter($"C:\\Work\\{fileName}");
using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture);
var options = new TypeConverterOptions { Formats = ["dd/MM/yyyy HH:mm:ss"] };
csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
DataTable dt = records.Tables[0];
foreach (DataColumn dc in dt.Columns)
{
csvWriter.WriteField(dc.ColumnName);
}
csvWriter.WriteField("Comment");
csvWriter.NextRecord();
var commentriesDataset = await ExecuteQuery(all_commentries_query, tableName);
var commentryRows = commentriesDataset.Tables[0].Rows;
int htmlCommentaryLength = 5000;
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
csvWriter.WriteField(dr[dc]);
}
string? commentryValue = dr["VariationReasonsCommentary"]?.ToString();
if (string.IsNullOrEmpty(commentryValue) == false)
{
bool notNumber = commentryValue.Any(x => char.IsDigit(x) == false);
if (notNumber)
{
csvWriter.WriteField(commentryValue.Length >= htmlCommentaryLength ? commentryValue[..htmlCommentaryLength] : commentryValue);
}
else
{
var commentryRow = commentryRows.Cast<DataRow>().Where(x => x["CommentaryID"].ToString() == commentryValue).FirstOrDefault();
if (commentryRow != null)
{
commentryValue = commentryRow?["Comment"].ToString();
csvWriter.WriteField(commentryValue?.Length >= htmlCommentaryLength ? commentryValue[..htmlCommentaryLength] : commentryValue);
}
else
{
csvWriter.WriteField("");
}
}
}
else
{
csvWriter.WriteField("");
}
csvWriter.NextRecord();
}








Dictionary<string, string>for fast commentary lookups and replace the loop withcsvWriter.WriteRecords()for batch writing to improve performance.