Skip to content

Using multiple lists in a single 'foreach'

Simon Mann

Asked Jun 19, 2008, 4:07 AM EDT1 answer
Share
LinkedInX
Hey there, I'm new and was wondering if someone coud help me out.

I was wondering whether it's possible to have two lists being parsed by the same foreach loop.

i.e.
foreach (Object obj in _objectList)

becoming

foreach (Object obj in _objectList, Client cli in _clientList)

The logic I'm trying to parse involves the method being able to call values from both lists and using them together. I tried calling two foreach loops, but they seem unable to share their data.

Cheers in advance for any help.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You may be better of using a for loop for this and not a foreach loop.

    for (int i = 0; i < objectList.Count; i++)
    {
       // Some processing code
       if (objectList[i] == clientList[i])
       {
          // Do something
       }
    }

    Of course the processing code I wrote is just there to show you that you can access both arrays using a single array indexer so you can make comparisons between them or whatever you need to do.
    0