使用yield在每组中循环

k-s*_*k-s 0 c# arrays loops yield

我有.ToArray()字符串,并希望在每个10项组中处理该列表.我很确定在这种情况下我可以使用yield但不确定如何.

我希望循环遍历100项.ToArray()并希望每组10个项目和流程.

下面是我的代码,但不知道如何使用yield对每个10项进行分组.

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

请建议.

Han*_*ing 7

您可以使用下面的扩展方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

 foreach(var group in Enumerable.Range(1,32).Batch(10)) { .. }
Run Code Online (Sandbox Code Playgroud)