Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate a loop every n items

Tags:

c#

loops

I have a list of items and I need to loop through it so that every n (eg. 3) items are first collected and then processed at once at the n'th item.

I'm doing the following:

List<MyObject> smallList = new List<MyObject>();

for (int i = 0; i < largeList.Count; i++)
{
    smallList.Add(largeList[i]);

    if (i % 3 == 0 || i >= largeList.Count - 3)
    {
        //Do somehting with those n items...
    }

    smallList.Clear();
 }

Is there a better way to do the above?

like image 814
Ivan-Mark Debono Avatar asked May 21 '16 09:05

Ivan-Mark Debono


People also ask

How do you iterate through a set of elements?

Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.

How do I loop through multiple lists at once?

Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.

How do you iterate through all items in a list python?

We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list.


2 Answers

You can also do this with LINQ:

var largeList = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
for (int i = 0; i < largeList.Count; i += 3)
{
    var items = largeList.Skip(i).Take(3).ToList();
    // do stuff with your 3 (or less items)
}
like image 180
kagelos Avatar answered Nov 03 '22 00:11

kagelos


I suggest using nested loops. Not as pretty as LinQ, but certainly faster.

const int n = 3;
var small = new List();
for(var i=0; i<large.Count; i+=n)
{
    small.Clear();
    for(var j=i; j < n && j<large.Count; j++)
        small.Add(large[j]);
    // Do stuff with small
}

However quite similar to what you have now. I think it doesn't get much butter than what you have.

like image 22
Toxantron Avatar answered Nov 02 '22 23:11

Toxantron