0

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.

4

3 回答 3

8

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)) { .. }
于 2013-11-13T08:35:16.523 回答
1

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.

于 2013-11-13T08:41:22.693 回答
0

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
}
于 2013-11-13T08:34:18.313 回答