I am having foreach loop on List like:
foreach( var e in myList){
//do something here but except element at myList[0]
}
and now I need to omit the loop for the element at first index. How can i achieve that?
Something like this?
foreach(var e in myList.Skip(1)){
}
If you need to skip elements at arbitrary indexes using for
would be more appropriate:
for(var index = 0; index < myList.Count; index++){
if (ShouldSkip(index))
continue;
// handle other elements as normal
}
If you need to skip just first - use .Skip(1) as shown in https://stackoverflow.com/a/27884993/477420
If you want to use foreach
with arbitrary indexes you can filter with .Where
:
foreach(var e in myList.Where((item, index) => index < 3 || index > 7))
{
...
}
You can as well try to use this:
foreach(var item in itemsList.Except(itemsToOmitList)){}
The good thing with using the above approach is that you will be able to omit multiple items irrespective of their index.