rulururu

post foreach loop with index

May 19th, 2010

Filed under: .NET — Kai @ 3:49 pm

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);  
            }
ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)