How to make a foreach loop with limit in c#?

Asked

Viewed 288 times

3

How can I make a limit foreach loop, for example I have a dictionary with 100 items and I want to make a loop of item 20 until 50 as I can do this in c#.

1 answer

10


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 further clarification, take a look at the documentation of foreach here and of for here.

And for a better understanding of the methods Skip() and Take() take a look here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.