如何分割在 foreach 循环中迭代的元素 [英] How do I segment the elements iterated over in a foreach loop

查看:50
本文介绍了如何分割在 foreach 循环中迭代的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历整个用户列表,但需要一次抓取 20 个.

I need to loop through an entire list of users, but need to grab 20 at a time.

foreach (var student in Class.Students.Take(20))
{
   Console.WriteLine("You belong to Group " + groupNumber);
   groupNumber++;
}

这样,前 20 个将属于第 1 组,第二个 20 将属于第 2 组,依此类推.

This way the first 20 will belong to Group 1, the second 20 to Group 2, and so on.

为此采取正确的语法吗?我相信 Take 需要 20 次才能完成.谢谢!

Is Take the correct syntax for this? I believe Take will take 20 then be done. Thanks!

推荐答案

你可以这样做:

int i = 0;
foreach (var grouping in Class.Students.GroupBy(s => ++i / 20))
    Console.WriteLine("You belong to Group " + grouping.Key.ToString());

这篇关于如何分割在 foreach 循环中迭代的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆