3
foreach (Process newprcs in oPrcs)
 {
  newprocid = (UInt32)newprcs.Id;
  if (!oNewProcs.Contains(newprocid))  //checking process id contain or not
    {
      oNewProcs.Add(newprocid);
      // MessageBox.Show(newprocid.ToString());
      uIdOfProcess = newprocid;
      //MessageBox.Show(uIdOfProcess.ToString(),"ProcessId");
      CInjector.HookingAPI(uIdOfProcess, "HookPrintAPIs.dll");
    }
}

2 Answers 2

9

It depends on the type of oPrcs. If it's a Process[] then it would be:

for (int i = 0; i < oPrcs.Length; i++)
{
    Process newprcs = oPrcs[i];
    ...
}

Otherwise, if the type of oPrcs implements IEnumerable<Process> (which it doesn't have to, admittedly - but it normally would) you'd get:

using (IEnumerator<Process> iterator = oPrcs.GetEnumerator())
{
    while (iterator.MoveNext())
    {
        Process newprcs = iterator.Current;
        ...
    }
}

Having said all that, I usually wouldn't convert a foreach loop into a for loop...

Sign up to request clarification or add additional context in comments.

4 Comments

+1 I rather throw in a counter somewhere if indexing is needed.
Would you convert a foreach into a for loop if you get this error: “Collection was modified; enumeration operation might not execute.”
@MikeBarnes: I would usually try to work out why I was getting that, and avoid it. Just changing it into a for loop would still be potentially dangerous.
@JonSkeet the error occurs when I try and add something to a Dictionary in a foreach. I only get the error when I loop over the second item. Going to create a stack post now.
4

Assuming that oPrcs is an IList<Process> (so it has a Count property and items can be accessed by index):

for (int i = 0; i < oPrcs.Count; i++)
{
    Process newprcs = oPrcs[i];
    if (!oNewProcs.Contains(newprocid))  //checking process id contain or not
    {
        oNewProcs.Add(newprocid);
        // MessageBox.Show(newprocid.ToString());
        uIdOfProcess = newprocid;
        //MessageBox.Show(uIdOfProcess.ToString(),"ProcessId");
        CInjector.HookingAPI(uIdOfProcess, "HookPrintAPIs.dll");
    }
}

1 Comment

To add to what FM said, it depends on what sort of collection you have. All collections supported by foreach do not have a Count or Length property.

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.