我必须以这种格式写出内容
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 :(得分:5)
是的,在foreach(或foreach in for)中嵌套for循环是正确的!
答案 1 :(得分:1)
在foreach循环中使用for循环是否正确?
循环内循环 - “嵌套循环” - 是一种常规方法。像C#这样的语言允许您在彼此内部自由地嵌套控制结构(循环,if
,...)。没有这个问题就很难解决。
唯一的危险是使函数变得冗长且难以理解和维护:解决方案是将内部控制结构分解为自己的方法。
答案 2 :(得分:0)
是的,除了我确保length1
和length2
在继续之前是平等的;)
你也可以这样做:
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();
}
但这只是炫耀,并没有真正让你的代码更清晰。我认为你的版本更好,更重要的是......
哦,并尝试运行代码,因为你的格式不合适,你需要先修改一下;)
答案 3 :(得分: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());
}