Foreach with takeN elements instead of 1

Let's say I have 23 items in a list. How can I foreach 5 elements each time and 3 elements for the last time? Is there something like the "takeN" method that I can use with foreach or something?

// myList is a list 23 elements
foreach (var x in myList) {
  // x is a list with 5 elements
}

      

+3
c #


source to share


5 answers


There is nothing in the structure, but you can use MoreLINQ Batch

:

foreach (var sublist in myList.Batch(5))
{
    // sublist has up to 5 elements
}

      



(On the last iteration, it will have only 3 elements.)

+4


source to share


Untested, but something like this:



        for (int i = 0; i < myList.Count; i += 5)
        {
            var sublist = myList.Skip(i).Take(5);
        }

      

+1


source to share


You can use a regular loop:

for(int i = 0; i < myList.Count; i += 5) { .. }

      

0


source to share


You can do this in two steps:

  • Create a value and index pair
  • Group values index/5

Excerpt:

var groups = myList.Select((x,i) => new {X=x, I=i/5})
                   .GroupBy(xi => xi.I, xi => xi.X);

      

Sample program:

using System.Linq;

namespace BatchLinq
{
    class Program
    {
        static void Main(string[] args)
        {

            var myList = Enumerable.Range(0, 23);
            var groups = myList.Select((x,i) => new {X=x, I=i/5})
                       .GroupBy(xi => xi.I, xi => xi.X);

            foreach (var group in groups)
                System.Console.Out.WriteLine("{{ {0} }}", string.Join(", ", group));
        }
    }
}

      

Output:

{ 0, 1, 2, 3, 4 }
{ 5, 6, 7, 8, 9 }
{ 10, 11, 12, 13, 14 }
{ 15, 16, 17, 18, 19 }
{ 20, 21, 22 }

      

0


source to share


Edit:

static IEnumerable<IEnumerable<T>> PrepareCollection<T>(List<T> input)
{
    int cnt = 0;

    while (cnt < input.Count)
    {
        IEnumerable<T> arr = input.Skip(cnt).Take(5);
        cnt += 5;
        yield return arr;
    }
}

      

0


source to share







All Articles