104

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 the first element of the collection. I would like to choose from which element foreach starts. Is it possible to somehow change the element from which foreach starts?

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
inferno
  • 1,221
  • 3
  • 9
  • 6
  • 1
    I would follow the principle of least astonishment: http://en.wikipedia.org/wiki/Principle_of_least_astonishment – ChaosPandion Jun 21 '11 at 17:53
  • If you don't start from the first element, how do you define the iterator's behavior? What happens when it reaches the end of the sequence? Does it then go back to the first element and iterate over the remaining elements? – Dan J Jun 21 '11 at 17:54
  • @ChaosPandion's comment is where I was going with those questions. :) – Dan J Jun 21 '11 at 17:56

5 Answers5

199

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))
Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
MoarCodePlz
  • 5,086
  • 2
  • 25
  • 31
  • Good call. WTB auto-complete (gahh can't remember the real name of it) in stackoverflow ;) – MoarCodePlz Jun 21 '11 at 17:56
  • Does this actually skip or does it just create a copy? I.E. would these two be different: `foreach(List row in rows.skip(1)){ row[0] = "newInfo"; }` vs `for(int i=1; i row = rows[i]; row[0] = "newStuff"; }` – TigerBear Oct 17 '16 at 11:47
28

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Jon, doesn't this run the risk of an exception if "sequence" is Null? – WEFX Dec 21 '15 at 18:34
  • @WEFX: Well we have no idea whether `sequence` can legitimately be `null` or not. Presumably the OP can handle that themselves - it's not really part of the question... – Jon Skeet Dec 21 '15 at 21:29
5

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Something like `IEnumerable SubTree(rootIndex)`? Good call! – Dan J Jun 21 '11 at 17:56
  • Thanks for answer, skip looks promising , reading MSDN information about skip I got to conclusion that maybe it is possible to write a method StartFrom(this IEnumerable tree, MyTreeElement element) which would be an extension method for IEnumerable which would return IEnumerable from which I should start iterating. Then maybe I could use this method as foreach(var element in tree.StartFrom(someElement))). – inferno Jun 21 '11 at 18:01
  • @inferno: Yes, you could easily do that. However, I would just add a method/property to MyTreeElement that was more like: `IEnumerable Children`, so you could just do: `foreach(var item in someElement.Children)` - much more clear than using extension methods IMO. – Reed Copsey Jun 21 '11 at 18:06
0

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47
  • This does not answer the question that was asked - the question doesn't mention `DataGridView` at all (or even a UI framework). – NightOwl888 Apr 17 '18 at 11:28
  • @NightOwl888 this was answered because the question was about skipping some iterations and iterating after that in foreach loop. In my example i just used Skip() to apply on DataGridView. – Junaid Pathan Sep 21 '18 at 11:28
-1

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.

Rob
  • 4,327
  • 6
  • 29
  • 55