0

I am trying to iterate through an array and process every X amount (in this case 90), then move go back though the loop until the array has been exhausted. This could be achieved easily if the array was a fixed amount, sadly it is not.

//Test range of 90 for total tag collection
        private void TestExcelRange(string[] tagCollection)
        {
            string DellTag = null;
            int maxGroupAmmount = 90;
            foreach(string singleTag in tagCollection)
            {
                //process in groups of 90 -- maxGroupAmmount

                if (singleTag != "NONE")
                {
                    DellTag += singleTag+ "|";
                }
                //After 90 process again until tagCollection is complete               
            }            
        }
jrider
  • 1,571
  • 1
  • 10
  • 26
  • 1
    Do you mean that you want to process the string[] in chunks of 90 elements? So if the array was size 100, then process 90 elements first and then process the last 10? – tmajest Feb 03 '16 at 01:18

1 Answers1

1

Here is a method that splits a list or array into chunks of a certain size:

public IEnumerable<IEnumerable<T>> GetChunks<T>(IEnumerable<T> elements, int size)
{
    var list = elements.ToList();
    while (list.Count > 0)
    {
        var chunk = list.Take(size);
        yield return chunk;

        list = list.Skip(size).ToList();
    }
}

You can then process your array like this:

private void TestExcelRange(string[] tagCollection)
{
    string DellTag = null;
    int maxGroupAmount = 90;
    var chunks = GetChunks(tagCollection, maxGroupAmount);

    foreach (IEnumerable<string> chunk in chunks)
    {
        //process in groups of 90      
    }            
}
tmajest
  • 360
  • 1
  • 5
  • This will work, but instead of creating so many nearly-full-length lists, why not use `ToArray` and then `Array.CopyTo` and avoid all the extra copying? Or do a fully-lazy implementation. – Ben Voigt Feb 03 '16 at 01:48