How to do a foreach loop with limit in C #?

3

How can I do a foreach loop with boundary, for example I have a dictionary with 100 items and I want to loop item 20 up to 50 how can I do this in C #.

    
asked by anonymous 18.06.2016 / 06:23

1 answer

8

Simple, try the following codes as examples:

Foreach Example 1:

foreach(ListViewItem lvi in listView.Items.Skip(20))
{
   //faça algo
   if (++itens == 50) break;
}

Foreach Example 2:

foreach(var itens in dicionario.Items.Skip(20).Take(50))

For:

for(int itens = 20; i <= 50 && i < dicionario.Items.Count; i++)
{
    ListViewItem lvi = dicionario.Items[i];
}

LINQ:

foreach( ListViewItem lvi in dicionario.Items.Cast<ListViewItem>().Skip(20).Take(50))
{
    //faça algo
}

For better clarification, take a look at the documentation for% here and the% with here .

And for a better understanding of the methods foreach and for take a look here .

    
18.06.2016 / 06:52