Apr 21, 2009

LINQ Versus the ForEach statement

I've been using LINQ, or at least LINQ to SQL for about a year and I love it. It made writing the database query portion of the application a breeze. I recently purchased Essential Linq by Charlie Calvert and Dinesh Kulkarni. In the early chapters they extoll the virtues of LINQ and how LINQ to objects can replace a lot of other code. 
Today I had to convert all the X values in a List. Normally I would do something like the following (where theData is my source  List and  converter.Convert() is a method that converts to my desired units):
            List new_list = new List(theData.Count);
            PointF new_point = new PointF();
            foreach (PointF data_pt in theData)
                new_point.X = (float)converter.Convert(data_pt.X);
                new_point.Y = data_pt.Y;
After thinking about it for a bit and experimenting it turned out I could replace all the above code with a single LINQ statement.
            List new_list = (from d in theData
                                         select new PointF((float) converter.Convert(d.X), d.Y)).ToList();
Now I just wish that Charlie had written his book a year ago (or maybe that I paid a little more attention when I was reading my first LINQ book).  

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.