I'm a junior developer currently working on a C# project. There is a lot more for me to learn so here I am looking for some advice on my code snippet.
I have a function that executes a number of processes and steps. I'm looking to log the execution of each step in a single string and insert that string into my database for daily review purposes. The code snippet below is able to accomplish this but looking at it, personally it is an eyesore and I'm sure there has to be a more efficient way to accomplish this but nothing comes to mind due to my lack of in depth knowledge. I was wondering if anybody could suggest a better alternative to forming the final "result" string.
Note: I removed the processes and functions involved in the original snippet to focus on the area I am looking to improve. The focus is purely on forming the "result" string. The output is as I expect it to be but I'm merely looking for a more efficient way to achieve it, alongside possibly learning something new. Any and all advice is appreciated.
Here is a sample of the possible final output: "Balloting IPO(s): 1005, 1006, 1007. Processed Tape for Share Issue Number(s): 1005 (Tape02), 1006 (Tape01). No Tape found for Share Issue Number(s): 1006."
if (ballotingIPOs.Count > 0)
{
string sBallotIPO = "Balloting IPO(s): ";
string sProcessTape = "Processed Tape for Share Issue Number(s): ";
string sNoTape = "No Tape found for Share Issue Number(s): ";
string tsBallotIPO = string.Empty;
string tsProcessTape = string.Empty;
string tsNoTape = string.Empty;
foreach (IPODetails ballotingIPO in ballotingIPOs)
{
tsBallotIPO += tsBallotIPO.Length > 0 ? $", {ballotingIPO.ShareIssueNumber}" : $"{ballotingIPO.ShareIssueNumber}";
if (ipoData.ipoDetails.ShareIssueNumber != null)
{
tsProcessTape += tsProcessTape.Length > 0 ? $", {ipoData.ipoDetails.ShareIssueNumber} (Tape{ipoData.ipoDetails.TapeNumber})" : $"{ipoData.ipoDetails.ShareIssueNumber} (Tape{ipoData.ipoDetails.TapeNumber})";
}
else
{
tsNoTape += tsNoTape.Length > 0 ? $", {ballotingIPO.ShareIssueNumber}" : $"{ballotingIPO.ShareIssueNumber}";
}
}
result += tsNoTape.Length > 0 ? $"{sBallotIPO}{tsBallotIPO}. {sProcessTape}{tsProcessTape}. {sNoTape}{tsNoTape}." : $"{sBallotIPO}{tsBallotIPO}. {sProcessTape}{tsProcessTape}.";
}
else
{
result += "No Balloting IPOs to process.";
}
StringBuilderrather thanstring. Also don't use$"{ballotingIPO.ShareIssueNumber}"- useballotingIPO.ShareIssueNumberinstead. \$\endgroup\$resultis undeclared. \$\endgroup\$.length > 0if you append (vice prepend) the comma, i.e.ballotingIPO.ShareIssueNumber + ", ". What does it matter that there will be a "dangling" comma at the very end. \$\endgroup\$elseby testing terminating conditions up front.if (ballotingIPOs.Count <= 0) return;\$\endgroup\$