This problem has bugged me for years, and I always feel like I'm coming up with a hack when there's a much better solution. The issue at hand occurs when you want to do something to all items in a list and then add something inbetween those items. In short, I want to:
- Do something to every item in the list.
- Do something else to all but the last item in the list (in effect, do something "inbetween" the items in the list).
For example, let's say I have a class called Equation
:
public class Equation
{
public string LeftSide { get; set; }
public string Operator { get; set; }
public string RightSide { get; set; }
}
I want to iterate over a list of Equation
s and return a string that formats these items together; something like the following:
public string FormatEquationList(List<Equation> listEquations)
{
string output = string.Empty;
foreach (Equation e in listEquations)
{
//format the Equation
string equation = "(" + e.LeftSide + e.Operator + e.RightSide + ")";
//format the "inbetween" part
string inbetween = " and ";
//concatenate the Equation and "inbetween" part to the output
output += equation + inbetween;
}
return ouput;
}
The problem with the above code is that it is going to include and
at the end of the returned string. I know that I could hack some code together, replace the foreach
with a for
loop, and add the inbetween
element only if it's not the last item; but this seems like a hack.
Is there a standard methodology for how to deal with this type of problem?