I’m performing a “while” loop in C#, this is going through some records being pulled from a DB. What’s the best way to detect/find the last record on the loop? Is this possible?
Here is my code:
while (sdr.Read())
{
//Pull each line from DB
the_title = sdr["the_title"].ToString();
the_cats = sdr["the_category"].ToString();
the_tags = sdr["the_tags"].ToString();
the_date = sdr["the_date"].ToString();
//Start file creation
writer.WriteLine("[");
writer.WriteLine("\"" + the_title + "\", ");
writer.WriteLine("\"" + the_cats + "\", ");
writer.WriteLine("\"" + the_tags + "\", ");
writer.WriteLine("\"" + the_date + "\", ");
writer.WriteLine("\"<a href=\\\"#\\\" class=\\\"sepV_a\\\" title=\\\"Edit\\\"><i class=\\\"icon-pencil\\\"></i></a>\"");
writer.WriteLine("],");
}
writer.WriteLine("]");
writer.WriteLine("}");
writer.Close();
The problem I’m having is with the last line of code “writer.WriteLine(“],”);” I need to remove that comma on the last record being pulled from the DB.
thank you
You can’t know the last (up until you’ve reached/passed it), but you can know the first. You can modify your code as:
Else, to avoid the check in every instance of the loop, you could use:
EDIT: Made clipping length dynamic by using
Environment.NewLine.Length.