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");
}
}
Add a comment
|
2 Answers
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...
4 Comments
mhenrixon
+1 I rather throw in a counter somewhere if indexing is needed.
Mike Barnes
Would you convert a foreach into a for loop if you get this error: “Collection was modified; enumeration operation might not execute.”
Jon Skeet
@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.Mike Barnes
@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.
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
mahju
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.