foreach loop with index
May 19th, 2010
I was fed up with declaring a “helper” variable for every foreach in which I needed a counter.
The solution is very cool I think:
My list of strings I’d like to iterate:
List<string> myStrings = new List<string>() { "abc", "def", "xyz" };
Old style:
int index = 0; foreach (string s in myStrings) { Console.WriteLine("{0}: {1}", index++, s); }
cool way using .net 3.5’s lambda syntax:
foreach (var o in myStrings.OfType<object>().Select((x, i) => new { x, i })) { Console.WriteLine("{0}: {1}", o.i, o.x); }





