I\'m thinking about implementing IEnumerable for my custom collection (a tree) so I can use foreach to traverse my tree. However as far as I know foreach always starts from
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.
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.
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.