1

Possible Duplicate:
C# foreach with index

I enjoy working the simplicity of foreach in C#, but I often need an index. Is there any way to combine these elegantly into one simple structure without doing the following:

for(var i = 0; i<items.Count; i++) {
    var item = items[i];

Or

int i = 0;
foreach(var item in items) {
    i++;

I'd imagine something neat like:

foreach(var item in items;int index) {
Community
  • 1
  • 1
Savage
  • 2,015
  • 1
  • 26
  • 33
  • foreach(var item in items){return items.index}.. something like this – Ashirvad Aug 23 '12 at 09:16
  • Other than samantic candy, what is the benefit? For Loop is for indexed access and the ForEach for object access - the ForEach does not allow changes to the collection during the loop, whereas the for loop does. What might be a better solution (if it were avaiable) would be a simple variable on the ForEach item to return its index, but I guess that then forces index order on the ForEach. – Wolf5370 Aug 23 '12 at 09:17
  • Yep, duplicate it seems. What do I do? Delete question? – Savage Aug 23 '12 at 09:49

1 Answers1

2

yes,

there's a neat extension method that i found here on SO:

foreach with index

works a bit like this (verbatim from previous answer):

public static void Each<T>( this IEnumerable<T> ie, Action<T, int> action )
{
    var i = 0;
    foreach ( var e in ie ) action( e, i++ );
}

and is used like:

var strings = new List<string>();
strings.Each(( str, n ) =>
{
    // hooray can capture 'n' as well as 'str'
});

or:

strings.Each((str, n) => Console.WriteLine(str));
Community
  • 1
  • 1
jim tollan
  • 21,831
  • 4
  • 43
  • 62