Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process a list with a loop, taking 100 elements each time and automatically less than 100 at the end of the list

Tags:

c#

loops

list

range

Is there a way to use a loop that takes the first 100 items in a big list, does something with them, then the next 100 etc but when it is nearing the end it automatically shortens the "100" step to the items remaining.

Currently I have to use two if loops:

for (int i = 0; i < listLength; i = i + 100) {     if (i + 100 < listLength)     {         //Does its thing with a bigList.GetRange(i, 100)     }     else     {         //Does the same thing with bigList.GetRange(i, listLength - i)     } } 

Is there a better way of doing this? If not I will at least make the "thing" a function so the code does not have to be copied twice.

like image 492
SecondLemon Avatar asked Jun 07 '15 14:06

SecondLemon


People also ask

How we create loops in Python using list?

Using for Loops You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.

Is iteration while loop?

The “while” loopA single execution of the loop body is called an iteration.

What is better than for loop?

List comprehensions are faster than for loops to create lists.

What can I use in place of for loops?

The most common way was to use for loop, iterate elements and find which is even. Instead of using for in this case, we can use the filter() method. This method also returns a new array.


1 Answers

You can make use of LINQ Skip and Take and your code will be cleaner.

for (int i = 0; i < listLength; i=i+100) {     var items = bigList.Skip(i).Take(100);      // Do something with 100 or remaining items } 

Note: If the items are less than 100 Take would give you the remaining ones.

like image 153
adricadar Avatar answered Sep 20 '22 15:09

adricadar