FizzBuzz in LINQ

Earlier this week I realized that you are able to define functions in LINQ queries. So I made myself a sweet little FizzBuzz in LINQ.

It’s not pretty code, but I had fun writing it. Though, the code would be a somewhat nicer without all the type declarations everywhere. Hehe, I guess that if your code reminds you of The Obfuscated Code Contest, it’s a pretty good sign that your code stinks. Clearly muda!


[TestMethod]
public void FizzBuzz()
{
var lines = from x in Enumerable.Range(1, 100)
let divides = new Func<int, int, bool>((denominator, nom) => nom % denominator == 0)
let fizz = new Func<int, Tuple<int, string>>(
n => new Tuple<int, string>(n, divides(3, n) ? "Fizz" : ""))
let buzz = new Func<Tuple<int, string>, Tuple<int, string>>(
tuple => new Tuple<int, string>(tuple.Item1, tuple.Item2 +
(divides(5, tuple.Item1) ? "Buzz" : "")))
let returnNumberIfEmptyString = new Func<Tuple<int, string>, string>(
tuple => tuple.Item2 == "" ? tuple.Item1.ToString() : tuple.Item2)
select returnNumberIfEmptyString(buzz(fizz(x)));

foreach (var line in lines)
{
Debug.WriteLine(line);
}
}

(Oh, forgot to say that I use the .NET 4.0 tuples for this post)

Advertisements

About gustafnk

Developer at Jayway, REST/Hypermedia, AWD, Software apprentice, Dvorak user, Christian atheist, Zizek fan. I'm on twitter: @gustaf_nk
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to FizzBuzz in LINQ

  1. Nice example of FizzBuzz, and great to see some .Net 4.0 code 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s