2012-06-28 2 views
2

Я выполняю цикл «while» в C#, это происходит через некоторые записи, извлекаемые из БД. Каков наилучший способ обнаружить/найти последнюю запись в цикле? Это возможно?Как обнаружить/найти конец цикла while?

Вот мой код:

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(); 

Проблема у меня есть с последней строкой коды «writer.WriteLine (»] «);» Мне нужно удалить эту запятую на последней записи, извлеченной из БД.

спасибо

+0

Что такое 'sdr'? –

+0

@EvanMulawski - Возможно, это 'SqlDataReader'. – Oded

+0

Совет. Используйте строку verbatim, чтобы спасти вас от всех обратных косых черт: '@" \ foo ... "' – gdoron

ответ

-1

Вы не можете знать, последний (до тех пор, пока вы достигли/прошло), но вы можете знать в первую очередь. Вы можете изменить свой код, как:

bool isFirst = true; 
while (sdr.Read()) 
{ 
    if (isFirst) isFirst = false; 
    else writer.WriteLine(","); 

    //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.Write("]"); 
} 
writer.WriteLine(); 

Else, чтобы избежать проверки в каждом случае петли, вы можете использовать:

var sb = new StringBuilder(); 
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 
    sb.AppendLine("["); 
    sb.AppendLine("\"" + the_title + "\", "); 
    sb.AppendLine("\"" + the_cats + "\", "); 
    sb.AppendLine("\"" + the_tags + "\", "); 
    sb.AppendLine("\"" + the_date + "\", "); 
    sb.AppendLine("\"<a href=\\\"#\\\" class=\\\"sepV_a\\\" title=\\\"Edit\\\"><i class=\\\"icon-pencil\\\"></i></a>\""); 

    sb.AppendLine("],"); 
} 
if (sb.Length > 0) 
{ 
    // Write result, sans characters for last newline (Environment.NewLine) and comma. 
    writer.WriteLine(sb.ToString(0, sb.Length - (Environment.NewLine.Length + 1)); 
} 

EDIT: Сделано длина отсечение динамический с помощью Environment.NewLine.Length.

+0

Мне нужно сохранить эту запятую на каждом блоке строк, кроме последней. Это сделает это для меня? – jorame

+0

@jorame Извините, я забыл запятую. Исправлено. Мне нужно будет дважды проверить, что «Длина - 2» - это правильная сумма для клипа, но в противном случае да, это сделает это. –

3

Сделай наоборот:

bool is_first = true; 

while (sdr.Read()) { 

    if (is_first) { 
     is_first = false; 
    } else { 
     writer.Write(","); 
    } 

    // Do your other writes here 
} 
+2

Это крайне неэффективный код. Подумайте о назначении переменной переменной (предпочтительно StringBuilder) и просто удалите последнюю запятую – Nas

+0

Это так же эффективно, как 'writer.WriteLine (" [");' is. Я не буду тратить время на запуск теста, но я уверен, что разница будет незначительной. –

+0

Это все о предсказании ветвления на уровне процессора. Это может помочь вам понять: http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array – Nas

2

Я предлагаю вам просто удалить последнего персонажа. Это наиболее эффективное решение в цикле.

StringBuilder sb = new StringBuilder(); 

    while (sdr.Read()) 
    { 
     sb.Append("Value"); 
     .... 
    } 

if(sb.Length > 0) 
{ 
sb.Remove(sb.Length - 1, 1) 
} 
var result = sb.ToString(); 
0

Другой подход, который должен работать:

List<String> bufferList = new List<String>(); 
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(); 

    StringBuilder tempSb = new StringBuilder(); 
    tempSb.AppendLine(); 

    //Start file creation 
    tempSb.AppendLine("["); 
    tempSb.AppendLine("\"" + the_title + "\", "); 
    tempSb.AppendLine("\"" + the_cats + "\", "); 
    tempSb.AppendLine("\"" + the_tags + "\", "); 
    tempSb.AppendLine("\"" + the_date + "\", "); 
    tempSb.AppendLine("\"<a href=\\\"#\\\" class=\\\"sepV_a\\\" title=\\\"Edit\\\"><i class=\\\"icon-pencil\\\"></i></a>\""); 
    tempSb.AppendLine(("]"); 

    bufferList.Add(tempSb.ToString()); 

} 

String.Join(",", bufferList); 
0

Еще один подход

if(sdr.Read()) { 
    while (true) { 
     ... 
     writer.WriteLine("["); 
     ... 
     if (!sdr.Read()) { 
      writer.WriteLine("]"); 
      break; 
     } 
     writer.WriteLine("],"); 
    } 
} 
Смежные вопросы