Partilhar via


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

canvas.FillRectangles(

    Brushes.Green,

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

   );

Comments

  • Anonymous
    January 22, 2006
    That's very cool. A reason to use the "Select" method rather than the SQL-style syntax that I hadn't considered.
  • Anonymous
    May 30, 2009
    PingBack from http://outdoorceilingfansite.info/story.php?id=2192
  • Anonymous
    June 03, 2009
    The comment has been removed