我如何段的元素在foreach循环遍历 [英] How do I segment the elements iterated over in a foreach loop

查看:118
本文介绍了我如何段的元素在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.

是对本正确的语法?我相信,以将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天全站免登陆