Alex Rivera | Logout

foreach with index

Asked 2009-02-06T19:01:31.660
191

Is there a C# equivalent of Python's enumerate() and Ruby's each_with_index?

Edit
Report

1 Answer

269

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
{
   if (it.Index > SomeNumber) //      
}

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection
answered 2009-02-06T19:04:28.130

Your Answer