Lucas Han Lucas Han - 3 months ago 15
C# Question

Format Structure for StringBuilder

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, String value)
{
if (client_file.output_format == "txt")
if (value = "the first value in add_value_to_row")
OutputCustomer.AppendFormat("{0}", value);
else if (value = "every other value in add_value_to_row")
OutputCustomer.AppendFormat("\t{0}", value);
}


I have a function written above that takes inputs from "x" and create data rows in .txt format according to the code below. I was wondering how I could write the nested if statements so that it performed what is written in quotes? The final output according to the data below should output "OutputCustomer.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}", x.url, x.company, x.Country, x.vendor, x.product);"

OutputCustomer = new StringBuilder();

add_value_to_row(clientInfo.cf, ref OutputCustomer, x.url);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.company);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.Country);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.vendor);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.product);

Answer

Why are you adding the items one by one? Give your object to the method and let it decide.

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, YourType value)
{
   if (client_file.output_format == "txt") 

     OutputCustomer.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}",
     value.url,value.company,value.Country,value.vendor,value.product); 

}

And call it like this

add_value_to_row(clientInfo.cf, ref OutputCustomer, x);

Otherwise you have to give a bool or int in the methods signiture

Update

If you really want to have your method the way it is you need a boolean in the signiture

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, String value, bool isFirst=false)
{
   if (client_file.output_format == "txt") 
      if (isFirst)
         OutputCustomer.AppendFormat("{0}", value); 
      else  
         OutputCustomer.AppendFormat("\t{0}", value);
}

And call it like this

add_value_to_row(clientInfo.cf, ref OutputCustomer, x.url, true);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.company);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.Country);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.vendor);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.product);

Also pay attention that you can have it as an optional parameter so you don't need to write it everytime