2012-06-28 3 views
2

C#에서 "while"루프를 수행 중이며 일부 레코드가 DB에서 가져 오는 중입니다. 루프에서 마지막 레코드를 검색/찾는 가장 좋은 방법은 무엇입니까? 이것이 가능한가? "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 ("]);": 여기

내 코드입니다 DB에서 가져온 마지막 레코드에서 해당 쉼표를 제거해야합니다.

bool is_first = true; 

while (sdr.Read()) { 

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

    // Do your other writes here 
} 
+0

은'sdr'은 무엇을? –

+0

@EvanMulawski - 아마도'SqlDataReader'입니다. – Oded

+0

팁, 축약 된 문자열을 사용하여 모든 백 슬래시를 저장하십시오.'@ "\ foo ..." – gdoron

답변

-1

당신은 (당신이 도달 한 최대 때까지 /를 통과) 마지막을 알 수는 없지만, 첫 번째를 알 수 있습니다 :

+0

마지막 줄을 제외하고 모든 줄 블록에 쉼표를 유지해야합니다. 이것은 나를 위해 그것을 할 것이냐? – jorame

+0

@jorame 죄송합니다, 쉼표를 잊었습니다. 고정 됐어. 나는 'Length - 2'가 정확한 길이라고 재확인 할 필요가있을 것이다. 그렇지 않으면 그렇다. –

3

주위를 다른 방법으로 수행 감사합니다. 으로 당신은 당신의 코드를 수정할 수 있습니다

그렇지
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(); 

는 루프의 모든 인스턴스에서 검사를 피하기 위해, 당신은 사용할 수 있습니다

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

편집 : Environment.NewLine.Length를 사용하여 제작 클리핑 길이 동적.

+2

이것은 매우 효율적인 코드입니다. 문자열을 변수 (StringBuilder 가급적이면)에 할당하고 마지막 쉼표 만 제거하는 것을 고려하십시오. – Nas

+0

'writer.WriteLine ("[");'만큼 효율적입니다. 나는 벤치 마크를 실행하는 데 시간을 낭비하지 않을 것이지만 그 차이는 무시할 수있을 것이라고 확신한다. –

+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("],"); 
    } 
} 
관련 문제