3

I have 2 foreach loops, 1 nested inside the other. There are 115 total items in 2 collections. 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}");
    }
}
6
  • 2
    please provide a minimal reproducible example Commented Jul 24, 2017 at 13:01
  • What is Text in the inner foreach? Commented Jul 24, 2017 at 13:05
  • One of the two collections? There are 115 total items in 2 collections? Commented Jul 24, 2017 at 13:05
  • 1
    I'm not guessing - it seems pretty clear to me! Commented Jul 24, 2017 at 13:07
  • Now it's been put on hold as "off-topic". @RodneyWilson I apologise for this kind of behaviour - it's for this reason I don't post so much on SO any more. Commented Jul 24, 2017 at 13:10

2 Answers 2

5

You need to know which item from the first collection is currently in use. This is simplest done by using a forloop.. You can then access the right item from the second collection:

for(int i = 0; i < Titles.Count; i++)
{
   Console.WriteLine($"Title: {Titles[i].Text}");
   Console.WriteLine($"Article Text: {Text[i].Text}");
}
Sign up to request clarification or add additional context in comments.

Comments

5

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}");
  }
}

1 Comment

@DavidG OMG, I feel so stupid right now! You are absolutely right. Assumed it to be Minbecause it kind of made sense to me :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.