C#X个项目后退出foreach循环 [英] C# Break out of foreach loop after X number of items

查看:77
本文介绍了C#X个项目后退出foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的foreach循环中,我想停止50个项目,当我达到第50个项目时,您如何打破这个foreach循环?

In my foreach loop I would like to stop after 50 items, how would you break out of this foreach loop when I reach the 50th item?

谢谢

foreach (ListViewItem lvi in listView.Items)

推荐答案

int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
   //do stuff
   if (++processed == 50) break;
}

或使用LINQ

foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
    //do stuff
}

或仅使用常规的for循环(如@sgriffinusa和@Eric J.所建议)

or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)

for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
    ListViewItem lvi = listView.Items[i];
}

这篇关于C#X个项目后退出foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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