-4
IEnumerable<MyRequest> myRequestsList = myRequests;

foreach (MyRequest request in myRequests)
{
    myResults.Add(ProcessMyRequest(userId, request));
}

please convert it to for loop in a better way

rafi muhammad
  • 194
  • 2
  • 11
  • 6
    Well, what is the original type of `myRequests`? *Why* are you trying to convert the loop into a for loop? Do you know how the compiler expands `foreach` loops? – Jon Skeet Nov 03 '15 at 07:08
  • No i don't know please explain me. – rafi muhammad Nov 03 '15 at 07:08
  • 1
    See http://stackoverflow.com/questions/398982 – Jon Skeet Nov 03 '15 at 07:10
  • There are a number of possible ways to change code using `foreach` into code using simply a `for` loop. None seem obviously _better_ than using `foreach`, and the ones that seem obvious to me all also seem worse. If you want an answer, you should explain your question better; what form of `for` loop are you looking for, and what is your broader goal in changing the code in this way? – Peter Duniho Nov 03 '15 at 07:10
  • See also: [foreach](https://msdn.microsoft.com/library/ttw7t8t6.aspx) – Corak Nov 03 '15 at 07:10
  • I wan to make it fast. – rafi muhammad Nov 03 '15 at 07:12
  • 1
    @rafi - why do you think `for` is faster than `foreach`? – Corak Nov 03 '15 at 07:13
  • My code just reviewed by my boss. He said to change like that. He said it will be a performance issue – rafi muhammad Nov 03 '15 at 07:16
  • `List myForList = myRequests.ToList(); for(int index = 0; index < myForList.Count; index++) { myResults.Add(ProcessMyRequest(userId, myForList[index])); }` will be oh so much faster you wouldn't believe it... (sorry for the sarcasm, but with bosses like that, you probably can't argue that this kind of premature optimization is just plain wrong) – Corak Nov 03 '15 at 07:21
  • For and foreach differ slightly in performance. They are approximately the same speed. But the foreach loop uses more stack space for local variables. –  Nov 03 '15 at 07:25
  • @NeillVerreynne - yes, full agreement on that. On the other hand, if the difference between `for` and `foreach` is the bottleneck, then we're in a whole other realm of performance (time *or* space) needs. – Corak Nov 03 '15 at 07:29
  • Speaking of optimization: use `MyRequest[] myForList = myRequests.ToArray();` instead. -- Also, hope that `myRequests` is finite. – Corak Nov 03 '15 at 07:31

1 Answers1

1

I got some bad news: if you insist on using IEnumerable you don't have a direct Count() function. You can use the code like this

for (int i = 0; i < myRequests.ToList<string>().Count; i++)
{
    // use the index!
}

But I think this is way more costly than the foreach(). The same answer suggests using ICollection over IEnumerable

Community
  • 1
  • 1
online Thomas
  • 8,864
  • 6
  • 44
  • 85