2012-04-27 253 views
0

我必須寫的內容在此格式在foreach循環運行的for循環

somename1 value1 value2 value1 value2 .... 
somename2 value1 value2 value1 value2 .... 
somename3 value1 value2 value1 value2 .... 
somename4 value1 value2 value1 value2 .... 
somename5 value1 value2 value1 value2 .... 

VALUE1和value2是一個點的x和y座標的一部分,所以這個我有創建了一個類:

class Points 
{ 
string name; 
double[] X; 
double[] Y; 
} 

class PointsCollection 
{ 
    List<Points> aPoints 
} 

//now when accessing the PointCollection 
foreach(Points aPoints in PointsCollection) 
{ 
    stream.Write(aPoints.Name) 
    //now i have to write the value1 and valud2 

} 

possible code 

//now when accessing the PointCollection 
foreach(Points aPoints in PointsCollection) 
{ 
    stream.Write(aPoints.Name) 
    int length1 = aPoints.Real; 
    int length2 = aPoints.Imag; 
    for(int i = 0 ; i < length1; i++) 
    { 
      stream.Write(aPoints.Real[i]); 
      stream.Write(","); 
      stream.Write(aPoints.Imag[i]); 

    } 
    stream.WriteLine(); 

} 

問題:在foreachloop中使用循環是否正確?

+0

可能會將內部循環移動到不同的方法,使它看起來整齊。 – Zenwalker 2012-04-27 07:59:12

回答

0

是的,除了我會確保length1length2正在着手面前一律平等;)

你也可以這樣做:

foreach(Points aPoints in PointsCollection) 
{ 
    stream.Write(aPoints.Name) 
    foreach (var complexNumber in aPoints.Real.Zip(aPoints.Imag, 
     (real, imag) => new { Real = real, Imag = imag })) 
    { 
     stream.Write(complexNumber.Real); 
     stream.Write(","); 
     stream.Write(complexNumber.Imag); 

    } 
    stream.WriteLine(); 
} 

但這僅僅是炫耀並沒有按」真的讓你的代碼更清晰。我想你的版本是更好,更重要的是...

哦,並嘗試運行代碼,因爲你的格式是關閉的重擊,你需要先鼓搗了一點;)

5

是,在foreach中嵌套for循環(或foreach for)是正確的!

1

在foreach循環中使用for循環是否正確?

循環內的循環 - 「嵌套循環」 - 是一種常規方法。像C#這樣的語言允許您將控制結構(循環,if,...)自由嵌套在一起。沒有這個問題很難解決。

唯一的危險是讓功能變得冗長難以理解和維護:解決方案是將內部控制結構分解爲自己的方法。

0

我將使用StringBuilder進行優化,並且只對每個循環的stream.Write()進行一次調用。
除此之外,讀取Real數組的長度時會出現一些錯誤,但我想這只是SO上的一個輸入錯誤。

StringBuilder sb = new StringBuilder(); 
//now when accessing the PointCollection 
foreach(Points aPoints in PointsCollection) 
{ 
    sb.Clear(); 
    sb.Append(aPoints.Name); 
    int length1 = aPoints.Real.Lenght; // Get the length of Real array 
    // int length2 = aPoints.Imag; // Not needed??? 
    for(int i = 0 ; i < length1; i++) 
    { 
     sb.AppendFormat("{0},{1} ", aPoints.Real[i], aPoints.Imag[i]); 
    } 
    sb.AppendLine(); 
    stream.Write(sb.ToString()); 
}