是否可以从第一个使用 foreach 的元素以外的其他元素开始迭代?

我正在考虑为我的自定义集合(一个树)实现 IEnumable,这样我就可以使用 foreach 遍历我的树。但是据我所知 foreach 总是从集合的第一个元素开始。我想选择 foreach 从哪个元素开始。有没有可能以某种方式改变 foreach 起始的元素?

78532 次浏览

Yes. Do the following:

Collection<string> myCollection = new Collection<string>;


foreach (string curString in myCollection.Skip(3))
//Dostuff

Skip is an IEnumerable function that skips however many you specify starting at the current index. On the other hand, if you wanted to use only the first three you would use .Take:

foreach (string curString in myCollection.Take(3))

These can even be paired together, so if you only wanted the 4-6 items you could do:

foreach (string curString in myCollection.Skip(3).Take(3))

You can use Enumerable.Skip to skip some elements, and have it start there.

For example:

foreach(item in theTree.Skip(9))  // Skips the first 9 items
{
// Do something

However, if you're writing a tree, you might want to provide a member on the tree item itself that will return a new IEnumerable<T> which will enumerate from there down. This would, potentially, be more useful in the long run.

It's easiest to use the Skip method in LINQ to Objects for this, to skip a given number of elements:

foreach (var value in sequence.Skip(1)) // Skips just one value
{
...
}

Obviously just change 1 for any other value to skip a different number of elements...

Similarly you can use Take to limit the number of elements which are returned.

You can read more about both of these (and the related SkipWhile and TakeWhile methods) in my Edulinq blog series.

Foreach will iterate over your collection in the way defined by your implementation of IEnumerable. So, although you can skip elements (as suggested above), you're still technically iterating over the elements in the same order.

Not sure what you are trying to achieve, but your class could have multiple IEnumerable properties, each of which enumerates the elements in a specific order.

If you want to skip reading Rows in a DataGridView, try this

foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow().Skip(3))

If you want to copy contents of one DataGridView to another skipping rows, try this,

foreach (DataGridViewRow row in dataGridView1.Rows.Cast<DataGridViewRow>().Skip(3))
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
dataGridView2.Rows[i].Cells[j].Value = cell.Value.ToString();
j++;
}
i++;
j = 0;
}

this copies the contents from one DataGridView to another skipping 3 rows.