問題描述
我正在考慮為我的自定義集合(一棵樹)實現 IEnumerable,以便我可以使用 foreach 遍歷我的樹.但是據我所知,foreach 總是從集合的第一個元素開始.我想選擇從哪個元素 foreach 開始.是否可以以某種方式更改 foreach 開始的元素?
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?
推薦答案
是的.執行以下操作:
Collection<string> myCollection = new Collection<string>;
foreach (string curString in myCollection.Skip(3))
//Dostuff
Skip
是一個 IEnumerable 函數,它可以從當前索引開始跳過您指定的任意數量.另一方面,如果你想使用 only 前三個你會使用 .Take
:
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))
這些甚至可以搭配在一起,所以如果你只想要 4-6 件,你可以這樣做:
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))
這篇關于是否可以從第一個使用 foreach 的元素以外的元素開始迭代?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!