多次替换foreach

时间:2019-02-25 12:48:28

标签: c# list for-loop arraylist foreach

我有一个函数,使用从列表中接收到的字符串以及列表中Point的X和Y坐标,在图片框上写入文本。

我正在尝试在第一个X和Y坐标处打印第一个字符串,在第二个x和y坐标处打印第二个字符串,依此类推。但是我不知道该怎么做。我使用下面的代码进行了尝试,但是它在每个坐标处绘制了所有字符串。

   Graphics g = pictureBox1.CreateGraphics();

   foreach (var str in outputstring)
    {
      foreach (var xpoint in cofgravX)
       {
        fx = (int)xpoint;

        foreach (var ypoint in cofgravY)
         {
           fy = (int)ypoint;

            listBox2.Items.Add(str);
            string drawString = str.ToString();
            Font drawFont = new Font("Arial", 16);
            SolidBrush drawBrush = new SolidBrush(Color.White);
            PointF drawPoint = new PointF(fx, fy);
            g.DrawString(drawString, drawFont, drawBrush, drawPoint);

          }
        }

     }

1 个答案:

答案 0 :(得分:2)

您不必嵌套循环。相反,您需要循环一次,然后从每个集合中获取所需的对象。这可以通过使用for循环和索引运算符来完成,也可以通过使用.Zip()作为LINQish样式来完成。

var outputstring = new List<string> { "Hello", "World" };
var cofgravX = new List<int> { 5, 20 };
var cofgravY = new List<int> { 5, 20 };

// As for loop
for (int i = 0; i < outputstring.Count; i++)
{
    var message = outputstring[i];
    var fx = cofgravX[i]; // This could throw an ArgumentOutOfRangeException
    var fy = cofgravY[i]; // This could throw an ArgumentOutOfRangeException

    // ToDo: Draw on graphics object
}


// LINQish way
var items = cofgravX
    .Zip(cofgravY, (X, Y) => new { X, Y })
    .Zip(outputstring, (Position, Message) => new { Position, Message });

// This will iterate as long as the shortest sequence of all three collection.
foreach (var item in items)
{
    var message = item.Message;
    var fx = item.Position.X;
    var fy = item.Position.Y;

    // ToDo: Draw on graphics object
}