GDI + LINQ = Generate a bar graph in a single line of code

This is a simplified version of actual code from an app I'm working on.  There are a few lines of setup, and then the cool part (the last statement): Using a select statement to iterate over a List<double>, creating a RectangleF object for each value, packaging them all into an Array, and passing the array to the FillRectangles method of the Graphics object.  All in a single line of code...

// Get values to draw

private List<double> performanceHistory = ReadPerformanceValues();


// Get the Graphics object to draw on

Bitmap bmp = new Bitmap(dimensions.Width,dimensions.Height);

Graphics canvas =  Graphics.FromImage(bmp);


// Scale the Graphics object according to the # of values

canvas.ScaleTransform(this.Size.Width/ performanceHistory.Count,1 );


// Create an array of RectangleF objects (one for each value) and pass them to FillRectangles



    performanceHistory.Select( (v,index) => new RectangleF((float)index, this.Size.Height - (float)v, 1F,  this.Size.Height)).ToArray()



Skip to main content