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?
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.
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.
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.
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With