I want to insert multiple "items" into a list using a foreach loop(looping over a list). Now I want to insert the lines as a <td>
element. But by specifying the index at the position I want to insert the line, the previous one gets overwritten. How can I add a line at position and then add the rest afterwards without overwriting the previously added line
private void Create_Driver_Report(string npcName)
{
var fileName = Get_Path("Driver_Reports.html");
var endTag = npcName;
var lineToAdd = "<!--New Line Here-->";
var htmlContent = File.ReadAllLines(fileName).ToList();
var index = htmlContent.FindIndex(x => x.Contains(lineToAdd));
htmlContent.Insert(index 1, endTag);
File.WriteAllLines("drivers.html", htmlContent);
}
How I want to do it in theory
foreach (Drivers item in drivers)
{
Create_Driver_Report($"<td>{item.Driver_ID}</td>");
Create_Driver_Report($"<td>{item.Driver_Name}</td>");
Create_Driver_Report($"<td>{item.Vehicle_ID}</td>");
Create_Driver_Report($"<td>{item.Company_ID}</td>");
Create_Driver_Report($"<td>{item.Company_Name}</td>");
}
CodePudding user response:
Override the ToString() method or create a new one.
If you always want to insert the same properties, seems unnecessary to invoke the Create_Driver_Report
over and over again.
public override String ToString() {
return
$"<td>{this.Driver_ID}</td>\n"
$"<td>{this.Driver_Name}</td>\n"
$"<td>{this.Vehichle_ID}</td>\n"
$"<td>{this.Company_ID}</td>\n"
$"<td>{this.Company_Name}</td>";
}
and you can invoke it like:
foreach (Drivers item in drivers) {
Create_Driver_Report(item.ToString());
}
Edit:
Option 1:
Use LINQ Select() and List.InsertRange()
public String ToHtmlRow() {
return
$"<tr><td>{this.Driver_ID}</td><td>{this.Driver_Name}</td><td>{this.Vehichle_ID}</td><td>{this.Company_ID}</td><td>{this.Company_Name}</td></tr>";
}
{
IEnumerable<string> lines = drivers.Select(driver => driver.ToString())
Create_Driver_Report(lines);
}
static void Create_Driver_Report(IEnumerable<string> lines) {
var fileName = Get_Path("Driver_Reports.html");
var lineToAdd = "<!--New Line Here-->";
var htmlContent = File.ReadAllLines(fileName).ToList();
var index = htmlContent.FindIndex(x => x.Contains(lineToAdd));
htmlContent.InsertRange(index 1, lines);
File.WriteAllLines("drivers.html", htmlContent);
}
Option 2:
You just add all of the rows you want and you call the Create_Driver_Report
only once.
List<String> toAdd = new List<String>();
foreach (Drivers item in drivers) {
toAdded.Add(item.ToHtmlRow());
}
Create_Driver_Report(String.Join("\n", toAdd));