Question

I have .ToArray() of string and want to process that list in each 10 items group. I am pretty sure that I can use yield in this case but not sure how to.

I want loop through 100 items of .ToArray() and want to each group of 10 items and process.

Below is my code but not sure how to group each 10 items using yield.

caseNumberList is string .ToArray()

 foreach (string commaString in ProcessGroup(caseNumberList, 10))
                            {
                                Console.Write(commaString); // 10 comma seperated items.
                                Console.Write(" ");
                            }

 public static IEnumerable<string> ProcessGroup(Array[] number, int limit)
        {
            int itemNum = 0;
            string caseNumbers = string.Empty;
            //
            // Continue loop until the exponent count is reached.
            //
            while (itemNum< limit)
            {
                caseNumbers = caseNumbers + number[itemNum];
                yield return caseNumbers;
            }
        }

Please suggest.

Was it helpful?

Solution

You could use an extension method like below around it:

public static IEnumerable<List<T>> Batch<T>(this IEnumerable<T> list, int size)
{
    List<T> batch = new List<T>(size);
    foreach(var item in list)
    {
       batch.Add(item);
       if (batch.Count >= size)
       {
         yield return batch;
         batch = new List<T>(size);
       }
    }

    if (batch.Count > 0)
      yield return batch;
}

Sample usage:

 foreach(var group in Enumerable.Range(1,32).Batch(10)) { .. }

OTHER TIPS

Although I prefer @HansKestings answer it is possible to achieve what you want by just modifying your code a little bit:

for(int i = 0; i < caseNumberList.Length; i+=10) {
    foreach (string commaString in ProcessGroup(caseNumberList, i, 10))
    {
        Console.Write(commaString);
        Console.Write(",");
    }

    Console.Write("\r\n");
}

static IEnumerable ProcessGroup(int[] number, int startindex, int limit)
{
    int itemNum = startindex;
    int iterations = 0;
    string caseNumbers = string.Empty;
    //
    // Continue loop until the exponent count is reached.
    //
    while (iterations < limit)
    {
        caseNumbers = caseNumbers + number[itemNum];
        itemNum++;
        iterations++;
        yield return caseNumbers;
    }
} 

Added another for-loop to keep track of the array index and altered ProcessGroup to accept an integer: the array index where it should start.
You may want to put the hardcoded 10 into a variable.

try this code,

var howMuch = 10;

var count = caseNumberList.Count();
int times = count/howMuch;

var listOfLists = new List<IEnumerable<string>>();
for (int i = 0; i < times; i++)
{
    listOfLists.Add(caseNumberList.Skip(howMuch * i).Take(howMuch));
}


foreach (var tenElementArray in listOfLists)
{
     //... do the logic
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top