float [] pt1x = {0.580f, 0.680f, 0.780f};
float [] pt1y = {1.128f, 1.228f, 1.328f};
foreach (float xpt in pt1x) {
System.Console.WriteLine("xpt = " + xpt);
foreach (float ypt in pt1y) {
System.Console.WriteLine("ypt = " + ypt);
}
}
------my output:
xpt = 0.58
ypt = 1.128
ypt = 1.228
ypt = 1.328
xpt = 0.68
ypt = 1.128
ypt = 1.228
ypt = 1.328
xpt = 0.78
ypt = 1.128
ypt = 1.228
ypt = 1.328
---------------here is what I NEED
to get below:
xpt = 0.58
ypt = 1.128
xpt = 0.68
ypt = 1.228
xpt = 0.78
ypt = 1.328
答案 0 :(得分:6)
float [] pt1x = {0.580f, 0.680f, 0.780f};
float [] pt1y = {1.128f, 1.228f, 1.328f};
for (int i=0; i < pt1x.Length; i++)
{
Console.Writeline("xpt = " + pt1x[i]);
Console.Writeline("ypt = " + pt1y[i]);
}
答案 1 :(得分:2)
for(int i = 0; i < pt1x.Length; i++)
Console.WriteLine(string.Format("{0} {1}",pt1x[i],pt1y[i]);
你正在做的事情:(注意缩进)
for each x
print x
for each y
print y
但你应该使用System.Drawing.Point
答案 2 :(得分:2)
如果转到.NET 4.0,则可以使用Enumerable.Zip method,否则可以将其作为.NET 3.5中的扩展方法实现。 Eric Lippert在他的博客文章Zip Me Up中给出了这种实现的一个例子。
以下是它的使用方法:
float[] pt1x = {0.580f, 0.680f, 0.780f};
float[] pt1y = {1.128f, 1.228f, 1.328f};
var result = pt1x.Zip(pt1y, (xpt, ypt) =>
"xpt = " + xpt + Environment.NewLine + "ypt = " + ypt);
foreach (var item in result)
Console.WriteLine(item);
请注意,您可能希望在lambda表达式的并置部分中将xpt
更改为xpt.ToString()
(ypt
相同),以便更好地控制返回类型。
编辑:切换实施链接到Eric Lippert的帖子,因为它在继续之前检查参数。
答案 3 :(得分:0)
嵌套循环不是你想要的。对于外循环的每个元素,内部循环将完全运行。
如果两个数组的元素数量相同,只需执行一个循环,并同时对两个数组执行所有操作。
for (int i = 0; i < pt1x.Length; i++)
{
System.Console.WriteLine("xpt = " + pt1x[i]);
System.Console.WriteLine("ypt = " + pt1y[i]);
}
答案 4 :(得分:0)
这是一个有点强大的解决方案(使用与其他人已经提供的相同的原则,但对于任意数量的数组):
static IEnumerable<T[]> AlignArrays<T>(params T[][] arrays) {
if (arrays == null)
throw new ArgumentNullException("arrays");
int numArrays = arrays.Length;
if (numArrays < 1)
yield break;
T[] firstArray = arrays[0];
for (int i = 0; i < firstArray.Length; ++i) {
T[] aligned = new T[numArrays];
for (int j = 0; j < numArrays; ++j) {
T[] thisArray = arrays[j];
if (i < thisArray.Length)
aligned[j] = thisArray[i];
else
aligned[j] = default(T);
}
yield return aligned;
}
}
用法:
float [] pt1x = {0.580f, 0.680f, 0.780f};
float [] pt1y = {1.128f, 1.228f, 1.328f};
foreach (float[] aligned in AlignArrays<float>(pt1x, pt1y)) {
for (int i = 0; i < aligned.Length; ++i)
Console.WriteLine(aligned[i]);
}
输出:
0.580
1.128
0.680
1.228
0.780
1.328
答案 5 :(得分:-1)
这看起来像价值对。 Dictionary<float, float>
不是更好吗?
Dictionary<float, float> floats = new Dictionary<float, float>();
floats.Add(0.580f, 1.128f);
floats.Add(0.680f, 1.228f);
floats.Add(0.780f, 1.328f);
floats.Keys.ToList().ForEach(f =>
{
Console.WriteLine(String.Format("key: {0} value: {1}", f, floats[f]));
});