sometimes we need to pick “n” number of items from a list of “N” items and perform some operation on the “n” items and repeat the same operation on the remaining items, i encountered this kind of scenario and the following code in C# can be used.
Consider a list of items with 23 items and you need 4 each time and perform operation on those 4.
var listOfItems = new List<int>();
for (int i = 1; i <= 23; i++)
{
listOfItems.Add(i);
}
for (int i = 0; i < listOfItems.Count; i = i + 4)
{
var items = listOfItems.Skip(i/4 * 4).Take(4);
foreach (var item in items)
{
Console.WriteLine(item);
}
Console.WriteLine($"Completed taking required {items.ToList().Count}");
}
Console.Read();
Code language: PHP (php)
the output of the above code will look like this
1
2
3
4
Completed taking required 4
5
6
7
8
Completed taking required 4
9
10
11
12
Completed taking required 4
13
14
15
16
Completed taking required 4
17
18
19
20
Completed taking required 4
21
22
23
Completed taking required 3
Here first we insert into listOfItems 23 values and later iterate over the list to take 4 each item and in the last iteration we are only left with 3 and those 3 are taken