formatting string builder in a For loop - c#

I have a function for my webform which outputs each item within my cart using a for loop. However, my problem is to format this string so it includes tabs spaces, and a new line for each item in the cart. My code stands as this:
public string Display()
{
CartClass CartList = CartClass.GetCart();
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < CartList.CartList.Count(); i++)
{
Movies Movie = CartList.CartList[i];
sb.Append(String.Format(i + 1 + "." + "\t"
+ Movie.MovieName + "\t" + "£" + Movie.MovieCost.ToString() + "\n" ));
}
return sb.ToString();
}
also to note that I output this string within a asp:listbox using this function
private void DisplayCart()
{
lstCart.Items.Clear();
lstCart.Items.Add(cart.Display());
}
and my out come is this
I'd like the format to resemble a list. For example
Up £5
Madagascar £5
Finding Nemo £5
how can I solve this?

It is not clear what you want in your line to be displayed, but assuming that you want a progressive number, the MovieName and its cost formatted with the current currency symbol, you could use directly the AppendFormat method and the rules of composite formatting
for (int i = 0; i < CartList.CartList.Count(); i++)
{
Movies Movie = CartList.CartList[i];
sb.AppendFormat("{0}.\t{1}\t{2:C}\n", i+1, Movie.MovieName, Movie.MovieCost);
}
The key point here is that both string.Format and StringBuilder.AppendFormat require a format string with placeholders embedded in curly braces ({0}....{1}) where the arguments following the format specifier will be inserted.
See Composite Formatting
However, your problem is caused by adding the whole stringbuilder as one single item. The newline character doesn't break you string in two, it is simply ignored by the listbox items collection.
You need to add one item at time. ( or look at the answer of Mr. Carey)
private void DisplayCart()
{
lstCart.Items.Clear();
CartClass CartList = CartClass.GetCart();
for (int i = 0; i < CartList.CartList.Count(); i++)
{
Movies Movie = CartList.CartList[i];
lstCart.Items.Add(string.Format("{0}.\t{1}\t{2:C}",
i+1, Movie.MovieName, Movie.MovieCost);
}
}

Assuming you want to segregate each movie from the cart list and add each movie as an item to the ListBox, you can use yield return from within the for loop to output an enumerable instead of a composite string and then you can enumerate the list to add each item to the ListBox.
You can do something like:
public IEnumerable<string> Display()
{
CartClass CartList = CartClass.GetCart();
for (int i = 0; i < CartList.CartList.Count(); i++)
{
Movies Movie = CartList.CartList[i];
yield return String.Format(i + 1 + "." + "\t"
+ Movie.MovieName + "\t" + "£" + Movie.MovieCost.ToString() + "\n" );
}
}
And then in the DisplayCart function:
private void DisplayCart()
{
lstCart.Items.Clear();
foreach (var movie in cart.Display())
{
lstCart.Items.Add(movie);
}
}

Assuming you'r using an ASP.Net ListBox control...
Well, any sequence of 1 or more whitespace characters save is, per the HTML spec, collapsed to a single SP (0x20) character when displayed on an HTML page. So there' not much point in differentiating between HT (tab) and SP.
What you probably want to do is to use data binding to populate your listbox. In which case your code becomes something like this:
CartClass cart = CartClass.GetCart() ;
IEnumerable<Movie> movies = cart.CartList ;
lstCart.DataSource = movies;
lstCart.DataTextField = <property-to-be-displayed-to-user>
lstCart.DataValueField = <property-to-be-used-when-item-is-selected>
lstCart.DataBind();
If you really want to format a string, you might look at doing something like this:
public string Display()
{
CartClass cart = CartClass.GetCart();
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < cart.CartList.Count() ; i++ )
{
Movie movie = cart.CartList[i];
sb.AppendFormat("{0}.\t{1}\t{2:C}" , i+1 , movie.MovieName , movie.MovieCost ).AppendLine() ;
}
return sb.ToString();
}
The C format specifier is "currency". Assuming you're in the UK, your default CultureInfo should format the movie cost as a proper UK price/currency value.

Related

Blank space is not displayed the same in the console output and in listbox

I am writing code to automate the code of PLSQL basic structure.
So i have a list which holds the parameters, example as below,
pv_student_name IN VARCHAR2
pn_number OUT NUMBER
So the parameters must be properly aligned as above, So I have written a procedure (method) in c# which takes plain input and align the parameters and returns a list with properly aligned parameters.
But When I print in the Console using System.Console.WriteLine then the parameters are aligned properly But when I see the parameters in a List Box the parameters are not aligned properly , though the spaces are added.
Below is the alignment code.
//Alignment of parameters logic
private List<string> alignParameters(List<string> nonAligned_parameters){
List<string> alignedParamtersList = new List<string>();
List<string> parameterList = new List<string>();
List<string> inOutList = new List<string>();
List<string> dataTypeList = new List<string>();
foreach (string parameter in nonAligned_parameters)
{
string[] param = parameter.Split(' ');
int count = 1;
foreach (string word in param)
{
if (count == 1)
{
parameterList.Add(word.Trim());
}
else if (count == 2)
{
inOutList.Add(word.Trim());
}
else if (count == 3) {
dataTypeList.Add(word.Trim());
}
count++;
}
}
// find the longest string in the list
int maxLength = parameterList.Max(x => x.Length);
//aligning the parameters
int numberOfElements= parameterList.Count();
for (int i = 0; i < numberOfElements; i++)
{
string param = parameterList[i].ToString().Trim();
string inOut = inOutList[i].ToString().Trim();
string dataType = dataTypeList[i].ToString().Trim();
int requiredSpace = maxLength - param.Length + 1;
string spaces = new string(' ', requiredSpace);
string spc = "";
if ("OUT".Equals(inOut)) {
spc = " ";
}
else if ("IN".Equals(inOut)) {
spc = " ";
}
string alignedParameter = param +
spaces +
inOut +
spc +
dataType;
// adding aligned parameters in aligned parameter list to be returned
alignedParamtersList.Add(alignedParameter);
}
return alignedParamtersList;
}
Below is the procedure where it is called, when we add a new parameter then the parameter is added, aligned and then populated back in the ListBox
private void button_AddParameter_Click(object sender, EventArgs e)
{
string error = "N";
//validation code here
if ("N".Equals(error)) {
parameterName = label_paramPrefix.Text +
textBox_parameterName.Text +" "+
combo_InOut.SelectedItem.ToString()+" "+
combo_DataType.SelectedItem.ToString();
}
parameterList.Add(parameterName);
// Align the parameters
parameterListAligned = alignParameters(parameterList);
// populating parameter list in GUI with fresh aligned parameters
listBox_parameter.Items.Clear();
foreach (string parameters in parameterListAligned)
{
listBox_parameter.Items.Add(parameters);
System.Console.WriteLine("param" + parameters);
}
}
So the problem is that even if the Console outputs the parameters aligned properly, the ListBox doesn't.
Can you guys please help me with this, I need those parameters to appear aligned in the ListBox as well.
Screen shot of the application where we can see the parameters not aligned in the ListBox is attached. and console output screenshot is also attached below that.
All you need is to use a monospace font, you can change the font of a listview from its properties windows (choose the listview in visual studio and click F4) and then change the font to something like 'Courier'.

append ". " after selected item values of checkbox list

I have a check box list item with List items in it. When i save the form selected values should be save to database .
See my logic.
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
It is working great but because of the "," which is i am putting between two values they are separated with each other, but at last item also it will append the "," . Is there any way to remove last "," or insert "." at last ","
Is there any logic for doing this?
Join all selected items, using string.Join and LINQ:
Type = string.Join(",",
chbCourse.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Text));
Since string.Join only adds the separator between items, it won't add an extra comma to the end.
(Also, calling ToString() on a ListItem displays the class type; you have to use the Text property.)
void Main()
{
var a="1,2,3,";
a=a.TrimEnd(new [] {','});
Console.WriteLine (a); //1,2,3
}
Do it like this for selected items:
string Type = string.Join(",", CheckBoxList1.Items.Cast<ListItem>().Where(a=>a.Selected).Select(a => a.Text));
if (!string.IsNullOrEmpty(Type)) // To add '.' at end
Type = Type + ".";
The easiest way is to use String.Join:
string Type = String.Join(",", chbCourse.Items);
If "." is also required
string Type = String.Concat(String.Join(",", chbCourse.Items),".");
If I'd wanted to put dot (".") on the last character, then I would do:
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
if (i == chbCourse.Items.Count - 1) Type += chbCourse.Items[i].ToString() + ".";
else
Type += chbCourse.Items[i].ToString() + ",";
}
}
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
if(Type != null)
Type = Type.TrimEnd(',');
Try not to use Class Names as variable names.
How about
string Type = null;
type = String.Join(",",
chbCourse.Items.Where(Function(x) x => x.Selected)
.Select(Function(y) y => y.ToString()).ToArray);

Using one array to track 3 pieces of data

I need your help with using one array to track 3 pieces of data. I have o use one array because it is school assignment and I am required to do so.
The array has to track Province ID, Region ID and the population for each region. There is 13 province and in each province there is 48 regions. Since the array is fixed size, I used a 624 by 3 multi dimensional array. The first column is for the provinceID, the second is for the regionID, and the third one is for the population.. I set the rows to 624 because there is 13 province and 48 regions in each province so 13*48 = 624.
I was able to insert my data and display them like this
ProvinceID # 1 RegionID # 1: 125000
Instead I would like to display the regions and population by province.
Something like this:
ProvinceID #1
RegionID # 1: 12000
RegionID # 2: 30000
ProvinceID #2
RegionID #1: 14000
RegionID #: 145000
Here is what I did
I declare a global array
int[,] census;
I initialize it on form initialize
census = new int[624,3];
Here is my insert
try
{
// declare variables
int prov, region, population;
prov = Convert.ToInt32(txtProvinceID.Text);
region = Convert.ToInt32(txtRegionID.Text);
population = Convert.ToInt32(txtPopulation.Text);
census[counter, 0] = prov;
census[counter, 1] = region;
census[counter, 2] = population;
counter++;
MessageBox.Show("Population " + txtPopulation.Text.ToString() + " saved for Province #" + txtProvinceID.Text.ToString()
+ " , Region #" + txtRegionID.Text.ToString(), "Success!");
txtRegionID.Clear();
txtProvinceID.Clear();
txtPopulation.Clear();
txtProvinceID.Focus();
}
catch (Exception ex)
{
if (ex.Message == "Input string was not in a correct format.")
{
MessageBox.Show("Please enter a numeric value", "Error");
}
else
{
MessageBox.Show(ex.Message, "Error");
}
}
This is the code to retrieve the data and save them to a file
string output = "";
try
{
for (int rows = 0; rows < census.GetLength(0); rows++)
{
for (int columns = 0; columns < census.GetLength(1); columns++)
{
if (census[rows, columns] != 0)
{
if (columns == 0)
{
output += "Province ID #" + census[rows, columns];
}
else if (columns == 1)
{
output += "Region ID #" + census[rows, columns] + ": ";
}
else if (columns == 2)
{
output += census[rows, columns] + "\n";
}
}// END if census[rows, coloumns]!=0
}// END for coloumns
}//END for(int row =0
// save the data to a text file
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled";
sfd.Filter = "Text (*.txt)|*.txt|Word Doc (*.doc)|*.doc";
sfd.DefaultExt = "txt";
sfd.AddExtension = true;
sfd.ShowDialog();
FileStream sf = new FileStream(sfd.FileName, FileMode.Create);
StreamWriter sw = new StreamWriter(sf);
sw.Write(output);
sw.Close();
}
catch (Exception)
{
}
Think of a table in which the rows are provinces and the columns are regions. And in each table cell is the population for that province/region. It would look like this
Region 1 Region 2 Region 3
Province 1 12000 13000 14000
Province 2 11320 9876 1234
Province 3 19723 32767 5038
Province 4 263 1284 1961
This exactly corresponds to a two-dimensional array:
int[,] census = new int[4,3];
And the values in the array would be, for example:
census[0,0] = 12000; // Province 1, Region 1
census[0,1] = 13000; // Province 1, Region 2
census[2,2] = 5038; // Province 3, Region 3
Modifying your code, you'd create your census array as:
int[,] census = new int[13, 48];
And to populate it:
prov = Convert.ToInt32(txtProvinceID.Text);
region = Convert.ToInt32(txtRegionID.Text);
population = Convert.ToInt32(txtPopulation.Text);
census[prov-1, region-1] = population;
Now, if you want to output by province and region:
StringBuilder output = new StringBuilder();
for (int prov = 0; prov < census.GetLength(0); prov++)
{
output.AppendLine("Province ID " + prov+1);
for (int region = 0; region < census.GetLength(1); ++region)
{
output.AppendLine(" Region #" + region+1 + " " +
census[prov, region]);
}
}
And then to output it, you open the file as you showed and Write(output.ToString()).
I used StringBuilder to construct the output rather than appending to a string. Appending strings is very expensive.
Also, you can simplify your file writing you using File.WriteAllText, like this:
// Show the Save File dialog box. And then,
File.WriteAllText(sfd.Filename, output.ToString());
There's no need to open a FileStream and then a StreamWriter. File.WriteAllText takes care of all that for you.
Update
To skip provinces that have no data, you write to a temporary StringBuilder and then append that to the final output only if there is data. For example:
StringBuilder output = new StringBuilder();
for (int prov = 0; prov < census.GetLength(0); prov++)
{
StringBuilder sbTemp = new StringBuilder();
for (int region = 0; region < census.GetLength(1); ++region)
{
if (census[prov, region] != 0)
{
sbTemp.AppendLine(" Region #" + region+1 + " " +
census[prov, region]);
}
}
if (sbTemp.Length > 0)
{
// At least one region had population, so add that
// and the province to the output.
output.AppendLine("Province ID " + prov+1);
output.Append(sbTemp);
}
}
The array has to track Province ID, Region ID and the population for each region.
This indicates that you should create a class to hold the three pieces of data. This way, it will be much easier to work with the array. Something like:
class Region
{
public int ProvinceId { get; set; }
public int RegionId { get; set; }
public long Population { get; set; }
}
Notice that I chose a different type for population, you wouldn't be able to do this with a simple array and you're certainly going to need something like that sooner or later.
When you have that, you can use LINQ to create groups of regions from the same province:
Region[] regions = …; // or maybe List<Region>
var regionGroups = regions.GroupBy(r => r.ProvinceId);
var result = new StringBuilder();
foreach (regionGroup in regionGroups)
{
result.AppendFormat("Province ID #{0}\n\n", regionGroup.Key);
foreach (var region in regionGroup)
{
result.AppendFormat(
"Region ID #{0}: {1}\n", region.RegionId, region.Population);
}
}
return result.ToString();
Also, you should never ever do this:
catch (Exception)
{
}
If you need to handle some specific exceptions, handle those, but only those.
I think it is really difficult to do this with your current program design
i suggest you to use jagged arrays for storing the values since LINQ can not be used on 2D arrays
A jagged array is an "array of arrays"
string[][] census=new string[624][];
for(int i=0;i<624;i++)
{
census[i]=new string[3];
}
Now you can use LINQ to get the required data from the array
var match=from c in census
where c[0]=="Province ID Text"
from details in c
where details!="Province ID Text"
select details;
and print the values as follows
foreach(var i in match)
Console.WriteLine(i);
If you are really particular on NOT using objects or database tables to store the values and
also don't want to use LINQ, the following solution might help you
void Select(string key)
{
for(int i=0;i<624;i++)
{
if(census[i][0]==key)
{
Console.Write(census[i][1]);
Console.Write(census[i][2]);
Console.WriteLine();
}
}
}
To eliminate duplicate data, we use a List to check whether that Province Id was previously checked or not
string done = "";
for (int i = 0; i < 624; i++)
{
if (!done.Contains(census[i][0]))
{
Console.WriteLine(census[i][0]);
Select(census[i][0]);
}
done=done+census[i][0];
}
I hope this code helps you but this is really NOT a good way to program.

comparing string and variable but failing based on contains

What I have going on is I have two files. Both files are delimited by '|'. If file 1 matches a line in file 2 I need to combine the lines. Here is the code:
string[] mathlines = File.ReadAllLines(#"C:\math.txt");
var addlines = File.ReadAllLines(#"K:\add.txt");
foreach (string ml in mathlines)
{
string[] parse = ml.Split('|');
if (addlines.Contains(parse[0]))
{
File.AppendAllText(#"C:\final.txt", parse[0]+"|"+parse[1]+"\n");
}
else
{
File.AppendAllText(#"C:\final.txt", ml + "\n");
}
}
I realize that the math part isn't setup yet, but I need to get the match part working.
Here is an example:
mathlines:
dart|504.91
GI|1782.06
Gcel|194.52
clay|437.35
grado|217.77
greGCR|14.82
rp|372.54
rp2|11.92
gsg|349.92
GSxil|4520.55
addlines:
Gimet|13768994304
GSxil|394735896576
Ho|4994967296
gen|485331304448
GSctal|23482733690
Obr|88899345920
As you can see mathlines contains GSxil and so does addlines but my if (addlines.Contains) never fines the variable in addlines. Any help is always loved! Thanks.
Sorry forgot to mention that I need it to match exactly on the comparison. Also i need to split out the variable on the correct line that matches. So I would need to split out the 394735896576 this example and then append the 394735896576.
addLines.Contains(parse[0]) is going to match on the entire string; you need to match based on part. There are more efficient solutions, but a O(n^2) option is to use LINQ Any():
if (addLines.Any(l => l.StartsWith(parse[0])))
{
...
You could load all lines from addlines.txt into a dictionary and then use that to find a match for each line in mathlines.txt. This method would be much faster than what you have currently.
string[] mathlines = File.ReadAllLines(#"C:\math.txt");
string[] addlines = File.ReadAllLines(#"K:\addlines.txt");
string[] finallines = new string[mathlines.Length];
var addlinesLookup = new Dictionary<string, string>();
for (int i = 0; i < addlines.Length; i++)
{
string[] parts = addlines[i].Split('|');
if (parts.Length == 2) // Will there ever be more than 2 parts?
{
addlinesLookup.Add(parts[0], parts[1]);
}
}
for (int i = 0; i < mathlines.Length; i++)
{
string[] parts = mathlines[i].Split('|');
if (parts.Length >= 1)
{
if (addlinesLookup.ContainsKey(parts[0]))
{
finallines[i] = mathlines[i] + "|" + addlinesLookup[parts[0]] + "\n";
}
{
finallines[i] = mathlines[i] + "\n";
}
}
}
File.AppendAllLines(#"C:\final.txt", finallines, Encoding.ASCII);

How do I iterate "between" items in an array / collection / list?

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 Equations 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?
You basically have a few different strategies for dealing with this kind problem:
Process the first (or last) item outside of the loop.
Perform the work and then "undo" the extraneous step.
Detect that your're processing the first or last item inside the loop.
Use a higher-level abstraction that allows you to avoid the situation.
Any of these options can be a legitimate way to implement a "between the items" style of algorithm. Which one you choose depends on things like:
which style you like
how expensive "undoing work" is
how expensive each "join" step is
whether there are any side effects
Amongst other things. For the specific case of string, I personally prefer using string.Join(), as I find it illustrates the intent most clearly. Also, in the case of strings, if you aren't using string.Join(), you should try to use StringBuilder to avoid creating too many temporary strings (a consequence of strings being immutable in .Net).
Using string concatentation as the example, the different options break down into examples as follows. (For simplicity, assume Equation has ToString() as: "(" + LeftSide + Operator + RightSide + ")"
public string FormatEquation( IEnumerable<Equation> listEquations )
{
StringBuilder sb = new StringBuilder();
if( listEquations.Count > 0 )
sb.Append( listEquations[0].ToString() );
for( int i = 1; i < listEquations.Count; i++ )
sb.Append( " and " + listEquations[i].ToString() );
return sb.ToString();
}
The second option looks like:
public string FormatEquation( IEnumerable<Equation> listEquations )
{
StringBuilder sb = new StringBuilder();
const string separator = " and ";
foreach( var eq in listEquations )
sb.Append( eq.ToString() + separator );
if( listEquations.Count > 1 )
sb.Remove( sb.Length, separator.Length );
}
The third would look something like:
public string FormatEquation( IEnumerable<Equation> listEquations )
{
StringBuilder sb = new StringBuilder();
const string separator = " and ";
foreach( var eq in listEquations )
{
sb.Append( eq.ToString() );
if( index == list.Equations.Count-1 )
break;
sb.Append( separator );
}
}
The last option can take multiple forms in .NET, using either String.Join or Linq:
public string FormatEquation( IEnumerable<Equation> listEquations )
{
return string.Join( " and ", listEquations.Select( eq => eq.ToString() ).ToArray() );
}
or:
public string FormatEquation( IEnumerable<Equation> listEquations )
{
return listEquations.Aggregate((a, b) => a.ToString() + " and " + b.ToString() );
}
Personally, I avoid using Aggregate() for string concatenation because it results in many intermediate, discarded strings. It's also not the most obvious way to "join" a bunch of results together - it's primarily geared for computing a "scalar" results from a collection in some arbitrary, caller-defined fashion.
You can use String.Join().
String.Join(" and ",listEquations.Select(e=>String.Format("({0}{1}{2})",e.LeftSide,e.Operator,e.RightSide).ToArray());
You can do this with LINQ's Aggregate operator:
public string FormatEquationList(List<Equation> listEquations)
{
return listEquations.Aggregate((a, b) =>
"(" + a.LeftSide + a.Operator + a.RightSide + ") and (" +
b.LeftSide + b.Operator + b.RightSide + ")");
}
Using a for loop with counter is perfectly reasonable if you don't want a foreach loop. This is why there is more than one type of looping statement.
If you want to process items pairwise, loop at LINQ's Aggregate operator.
I usualy add it before the condition, and check if its the 1st item.
public string FormatEquationList(List<Equation> listEquations)
{
string output = string.Empty;
foreach (Equation e in listEquations)
{
//use conditional to insert your "between" data:
output += (output == String.Empty) ? string.Empty : " and ";
//format the Equation
output += "(" + e.LeftSide + e.Operator + e.RightSide + ")";
}
return ouput;
}
I have to say I would look at the string.Join() function as well, +1 for Linqiness on that. My example is a more of a traditional solution.
I generally try to prefix separators based on a condition rather than add them to the end.
string output = string.Empty;
for (int i = 0; i < 10; i++)
{
output += output == string.Empty ? i.ToString() : " and " + i.ToString();
}
0 and 1 and 2 and 3 and 4 and 5 and 6 and 7 and 8 and 9
I like the String.Join method already posted.
But when you're not using an Array this has normally been my solution to this problem:
public string FormatEquationList(List<Equation> listEquations)
{
string output = string.Empty;
foreach (Equation e in listEquations)
{
// only append " and " when there's something to append to
if (output != string.Empty)
output += " and ";
output += "(" + e.LeftSide + e.Operator + e.RightSide + ")";
}
return output;
}
Of course, it's usually faster to use a StringBuilder:
public string FormatEquationList(List<Equation> listEquations)
{
StringBuilder output = new StringBuilder();
foreach (Equation e in listEquations)
{
// only append " and " when there's something to append to
if (output.Length > 0)
output.Append(" and ");
output.Append("(");
output.Append(e.LeftSide);
output.Append(e.Operator);
output.Append(e.RightSide);
output.Append(")");
}
return output.ToString();
}

Categories