2009-03-07 8 views
1

다음 C# 코드 조각에서
'foreach'루프 안에 'foreach'루프가 있고 특정 조건이 발생하면 'foreach'의 다음 항목으로 건너 뛰고 싶습니다.foreach 내부에서 계속 작업하십시오.

foreach (string objectName in this.ObjectNames) 
{ 
    // Line to jump to when this.MoveToNextObject is true. 
    this.ExecuteSomeCode(); 
    while (this.boolValue) 
    { 
     // 'continue' would jump to here. 
     this.ExecuteSomeMoreCode(); 
     if (this.MoveToNextObject()) 
     { 
      // What should go here to jump to next object. 
     } 
     this.ExecuteEvenMoreCode(); 
     this.boolValue = this.ResumeWhileLoop(); 
    } 
    this.ExecuteSomeOtherCode(); 
} 
continue ' continue'는 ' foreach'루프가 아닌 ' while'루프의 시작 부분으로 이동합니다. 여기에 사용할 키워드가 있습니까, 아니면 제가 정말로 좋아하지 않는 goto를 사용해야합니까?

답변

2

다음은 트릭

foreach (string objectName in this.ObjectNames) 
{ 
    // Line to jump to when this.MoveToNextObject is true. 
    this.ExecuteSomeCode(); 
    while (this.boolValue) 
    { 
     if (this.MoveToNextObject()) 
     { 
      // What should go here to jump to next object. 
      break; 
     } 
    } 
    if (! this.boolValue) continue; // continue foreach 

    this.ExecuteSomeOtherCode(); 
} 
8

break 키워드를 사용하십시오. 그것은 while 루프를 빠져 나와서 그것의 실행을 계속할 것이다. 잠시 후 아무 것도 없으므로 foreach 루프의 다음 항목으로 돌아갑니다.

실제로 예제를 자세히 살펴보면 while 루프를 진행하지 않고 for 루프를 진행할 수 있습니다. foreach 루프에서는이 작업을 수행 할 수 없지만 실제로 자동화하는 작업으로 foreach 루프를 세분화 할 수 있습니다. .NET에서 foreach 루프는 실제로 this.ObjectNames 객체 인 IEnumerable 객체에서 .GetEnumerator() 호출로 렌더링됩니다. 이 구조를 일단

IEnumerator enumerator = this.ObjectNames.GetEnumerator(); 

while (enumerator.MoveNext()) 
{ 
    string objectName = (string)enumerator.Value; 

    // your code inside the foreach loop would be here 
} 

, 당신은 다음 요소로 발전하기 위해 while 루프 내에서 enumerator.MoveNext()를 호출 할 수 있습니다

foreach는 루프이 기본적이다. 그래서 코드가 될 것이다 :

IEnumerator enumerator = this.ObjectNames.GetEnumerator(); 

while (enumerator.MoveNext()) 
{ 
    while (this.ResumeWhileLoop()) 
    { 
     if (this.MoveToNextObject()) 
     { 
      // advance the loop 
      if (!enumerator.MoveNext()) 
       // if false, there are no more items, so exit 
       return; 
     } 

     // do your stuff 
    } 
} 
+0

나는 내가 처음 추가 된 코드는 매우 정확하지 않습니다 죄송합니다. 건너 뛸 코드가 더 있습니다. 휴식을 사용하면 도움이되지 않습니다. 더 정확한 코드 스 니펫을 업데이트했습니다. – Amr

+2

나는 여분의 논리를 추가하지 않고도 문제를 해결할 때 대답을 좋아하지만; 나는 그것이 좋은 해결책이라고 생각하지 않는다. 나는 OP의 경우에 어떻게해야할지 모르겠다.하지만이 미친 논리가 처음부터 필요하지 않은 방식으로 코드를 구조화하는 것이 최선의 해결책이 될 것이다. – nlaq

+0

너무 나빠서 투표 수 없습니다 ... +1 @ 넬슨도. –

2

break; 키워드는 루프를 종료합니다 :

foreach (string objectName in this.ObjectNames) 
{ 
    // Line to jump to when this.MoveToNextObject is true. 
    while (this.boolValue) 
    { 
     // 'continue' would jump to here. 
     if (this.MoveToNextObject()) 
     { 
      break; 
     } 
     this.boolValue = this.ResumeWhileLoop(); 
    } 
} 
0

당신이 사용할 수있는 "휴식을;" 가장 안쪽이나 foreach를 종료합니다.

1

사용 goto을 수행해야합니다.

는 (나는 사람들이 응답 미친 것 같아요,하지만 난 확실히 다른 모든 옵션보다 더 읽을 생각합니다.)