How to convert foreach loop to for loop in C #

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");
    }
}
+3
source share
2 answers

It depends on the type oPrcs. If it is a Process[], then it will be:

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

Otherwise, if the type oPrcsimplements IEnumerable<Process>(to which it is not necessary, but, as a rule, it should turn out:

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

Having said all this, I usually did not convert the loop foreachto loop for...

+8
source

Assuming what oPrcsis IList<Process>(therefore, it has a property Count, and elements 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");
    }
}
+4
source

Source: https://habr.com/ru/post/1751508/


All Articles