如何将下面的循环限制为50,以便在到达第51项时停止?
foreach (ListViewItem lvi in listView.Items) { }
谢谢
Linq很容易
foreach (ListViewItem lvi in listView.Items.Take(50)) { }
从MSDN文档:
Take <(Of <(TSource>)>)枚举source和yield元素,直到count元素被生成或source不再包含元素.
如果count小于或等于零,则不枚举source并返回空的IEnumerable <(Of <(T>)>).
好吧,foreach可能不是最好的解决方案,但如果你必须:
int ctr = 0; foreach (ListViewItem lvi in listView.Items) { ctr++; if (ctr == 50) break; // do code here }
注意: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 }
foreach (ListViewItem lvi in listView.Items) { // do code here if (listView.Items.IndexOf(lvi) == 49) break; }
或者因为它是列表视图项
foreach (ListViewItem lvi in listView.Items) { // do code here if (lvi.Index == 49) break; }
使用Linq作为Per LukeDuff
foreach (ListViewItem lvi in listView.Items.Take(50)) { // do code here }
使用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 }
使用for循环.
for(int index = 0; index < collection.Count && index < 50; index++) { collection[index]; }
for(int index = 0, limit = Math.Min(50, collection.Count); index < limit; index++) { collection[index]; }