C#循环限制为50次传球

2 c# loops

如何将下面的循环限制为50,以便在到达第51项时停止?

foreach (ListViewItem lvi in listView.Items)
{

}
Run Code Online (Sandbox Code Playgroud)

谢谢

小智 23

Linq很容易

foreach (ListViewItem lvi in listView.Items.Take(50)) {

}
Run Code Online (Sandbox Code Playgroud)

从MSDN文档:

Take <(Of <(TSource>)>)枚举source和yield元素,直到count元素被生成或source不再包含元素.

如果count小于或等于零,则不枚举source并返回空的IEnumerable <(Of <(T>)>).


Arm*_*est 16

好吧,foreach可能不是最好的解决方案,但如果你必须:

int ctr = 0;
foreach (ListViewItem lvi in listView.Items) {
    ctr++;
    if (ctr == 50) break;

    // do code here

}
Run Code Online (Sandbox Code Playgroud)

注意:for循环通常比使用foreach遍历集合更轻.

最好使用for循环:

// loop through collection to a max of 50 or the number of items
for(int i = 0; i < listView.Items.Count && i < 50; i++){
    listView.Items[i]; //access the current item

}
Run Code Online (Sandbox Code Playgroud)


Tom*_*son 14

foreach (ListViewItem lvi in listView.Items) {
  // do code here
  if (listView.Items.IndexOf(lvi) == 49)
    break;
}
Run Code Online (Sandbox Code Playgroud)

或者因为它是列表视图项

foreach (ListViewItem lvi in listView.Items) {
  // do code here
  if (lvi.Index == 49) break;
}
Run Code Online (Sandbox Code Playgroud)

使用Linq作为Per LukeDuff

foreach (ListViewItem lvi in listView.Items.Take(50)) {
  // do code here
}
Run Code Online (Sandbox Code Playgroud)

使用For Loop作为Per Atomiton

// loop through collection to a max of 50 or the number of items
for(int i = 0; i < listView.Items.Count && i < 50; i++){
    listView.Items[i]; //access the current item

}
Run Code Online (Sandbox Code Playgroud)


Chu*_*way 7

使用for循环.

for(int index = 0; index < collection.Count && index < 50; index++)
{
   collection[index];
}
Run Code Online (Sandbox Code Playgroud)


Ori*_*ian 5

for(int index = 0, limit = Math.Min(50, collection.Count); index < limit; index++)
{
   collection[index];
}
Run Code Online (Sandbox Code Playgroud)