Thursday, November 29, 2007

Mandelbrot in LINQ to Objects

Inspired by LukeH's blog, I wanted to write a Mandelbrot generator in LINQ to Objects, just to get to know LINQ. Here it is:

var pixelsQuery = from y in Enumerable.Range(0, h)
let fy = (y - h / 2.0) / (h / 2.0)
select from x in Enumerable.Range(0, w)
let fx = (x - w / 2.0) / (w / 2.0)
let start = new MD { X = fx, Y = fy }
let mandel = (Func<md,>)((md, i) => (new MD {
X = md.X * md.X - md.Y * md.Y + start.X,
Y = 2 * md.X * md.Y + start.Y
}))
let z = Enumerable.Range(0, imax).Aggregate(start, mandel)
select new { X = x, Y = y, C = z.X < 4 ? Color.Black : Color.Wheat };

Thursday, August 16, 2007