简体   繁体   English

嵌套的Foreach循环运行次数太多 - C#

[英]Nested Foreach loop runs too many times - C#

I have 2 foreach loops, 1 nested inside the other. 我有2个foreach循环,1个嵌套在另一个循环中。 There are 115 total items in 2 collections. 共有115个项目共有115个。 What I'm wanting to do is have the first item from the first collection written to the console and then the first item from the second collection written to the console. 我想要做的是将第一个集合中的第一个项目写入控制台,然后将第二个集合中的第一个项目写入控制台。 Go back to the first collection and do the second item and so on. 返回第一个集合并执行第二个项目,依此类推。

I understand why the nested loop is running over and over, I just can't figure out how to achieve what I want to achieve. 我理解为什么嵌套循环一遍又一遍地运行,我只是无法弄清楚如何实现我想要实现的目标。

var Titles = chromeDriver.FindElements(By.CssSelector("div.contentItem__contentWrapper h1"));
var Text = chromeDriver.FindElements(By.CssSelector("div.contentItem__contentWrapper p"));        

foreach (var title in Titles)
{
    string t = title.Text;
    Console.WriteLine($"Title: {t}");
    foreach (var text in Text)
    {
        string p = text.Text;
        Console.WriteLine($"Article Text: {p}");
    }
}

You need to know which item from the first collection is currently in use. 您需要知道当前正在使用第一个集合中的哪个项目。 This is simplest done by using a for loop.. You can then access the right item from the second collection: 这是通过使用for循环最简单的方法。然后,您可以从第二个集合中访问正确的项目:

for(int i = 0; i < Titles.Count; i++)
{
   Console.WriteLine($"Title: {Titles[i].Text}");
   Console.WriteLine($"Article Text: {Text[i].Text}");
}

You should make it a single loop and iterate through both collections. 你应该把它作为一个循环并遍历两个集合。

for (var x = 0; x < Math.Max(Titles.Count, Text.Count); x++)
{
  if (Titles.Count > x)
  {
    Console.WriteLine($"Title: {Titles[x].Text}");
  }
  if (Text.Count > x)
  {
    Console.WriteLine($"Article Text: {Text[x].Text}");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM