Mohammad Zare
Mohammad Zare

Reputation: 1509

How to use for loop instead of foreach loop?

how can i implement this foreach loop with for loop? because i heard that for loop is much faster than foreach loop.

   foreach (RV item in gridview.SelectedItems.ToList())
   {
        R req= db.Requests.Single(x => x.Id == item.Id);
        ...
   }

Upvotes: 2

Views: 2453

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112352

There is no point in converting your selected items to a list, if you are enumerating them with foreach anyway. Also a for loop requires you to call ToList, which internally uses a foreach!

I do not know, if your o/r-mapper can cope with Contains. If it does try this:

var items = db.Requests.Where(x => gridview.SelectedItems.Contains(x.Id));

This will reduce the number of database requests. This is where time gets lost, not in the foreach!

Upvotes: 0

Martin
Martin

Reputation: 40335

for (int i = 0; i < gridview.SelectedItems.Count(); i++)
{
    R req = db.Requests.Single(x => x.ID == (gridview.SelectedItems(i) as RV).Id);
    ...
}

Although I doubt there will be any noticeable performance gain.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You heard incorrectly.
for loops are not much faster than foreach loops.
In fact, for some collections, foreach loops are much faster than for loops.

ToList() is slower than either of them.

If you really want to make your code faster, you should use an O(n) LINQ join instead of the O(n2) Single() call.

Upvotes: 11

Related Questions