【问题标题】:How to loop though a List如何循环遍历列表
【发布时间】:2012-04-01 04:46:19
【问题描述】:

谁能帮忙。

我有一个问题,我需要遍历 3 行并检查它们是否使用 C# 相交。 3 条线将构成三角形的一般形状。因此,一次只能有 2 条线相交。

我有 3 个 Line 对象,并将它们存储在 List 行中。 我目前检查交叉点的方法如下所示:

ProcessIntersections(lines[0], lines[1])
ProcessIntersections(lines[1], lines[2])
ProcessIntersections(lines[2], lines[0])

我可以循环遍历列表,但要检查最后的交叉点,我必须再次通过第一行并检查最后一行。

有没有更好的方法来处理我的交叉点? 我怎样才能通过只调用一次 ProcessIntersections 来遍历行列表? 我试过了:

for (int i = 0; i < lines.Count; i++)
{
    if (i >= 3)
    {
        i = 0;
        ProcessIntersection(lines[i], lines[i + 1]);
    }
}

但这只会让我陷入无限循环,因为我不断重置为 0。

有人有什么建议吗。

【问题讨论】:

  • 为什么多次调用ProcessInteractions 会出现问题?如果此方法比较两条线的交集,那么它完全符合您对第一个代码示例的要求。创建方法的重点是能够重用代码并使用不同的输入多次调用它
  • 如果你只有 3 行,那么 lines.Count = 3 --> 这意味着我永远不会 >= 3。

标签: c# list loops if-statement


【解决方案1】:

尝试下一个循环:

for (int i = 0; i < lines.Count; i++)
{
  var next_i = i + 1;
  if (next_i >= lines.Count)
    next_i = 0;
  ProcessIntersection(lines[i], lines[next_i]);
}

或优化循环:

for (int i = 0; i < lines.Count; i++)
{
  ProcessIntersection(lines[i], lines[(i + 1) % lines.Count]);
}

【讨论】:

    【解决方案2】:
    for (int i = 0; i < lines.Count; i++)
    {
            ProcessIntersection(lines[i], lines[i == lines.Count -1 ? 0 : i + 1]);
    }
    

    【讨论】:

      【解决方案3】:

      如果您想检查每一行及其后继行,然后检查最后一行的行[0],您可以这样做:

      for(int i = 0;i < lines.Count - 1;++i)
          ProcessIntersection(lines[i], lines[i + 1]);
      if(lines.Count > 1)
        ProcessIntersection(lines[lines.Count - 1], lines[0]);
      

      如果您真的希望在 for() 循环中处理所有内容(这会对速度产生负面影响),您可以这样做:

      for(int i = 0;i < lines.Count;++i)
        ProcessIntersection(lines[i], lines[i == lines.Count - 1 ? 0 : i + 1]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-22
        • 1970-01-01
        • 2011-02-28
        • 2018-09-05
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        相关资源
        最近更新 更多