Blog LogoBlog Logo

Fizz-Buzz in LINQ

16 Apr 2008 ~ 1 min read


This just occurred to me. It is somewhat pointless, but I thought it was interesting:

static void Main(string[] args)
{
    var result = from say in Enumerable.Range(1, 100)
                 select (say % 15 == 0)
                         ? "BuzzFizz"
                         : (say % 5 == 0)
                            ? "Buzz"
                            : (say % 3 == 0)
                               ? "Fizz"
                               : say.ToString();
    foreach (string say in result)
        Console.WriteLine(say);
}

Or, without the LINQ syntax, just the methods:

static void Main(string[] args)
{
    var result = Enumerable.Range(1, 100)
      .Select(say => (say % 15 == 0)
                      ? "BuzzFizz"
                      : (say % 5 == 0)
                         ? "Buzz"
                         : (say % 3 == 0)
                            ? "Fizz"
                           : say.ToString();
    foreach (string say in result)
        Console.WriteLine(say);
}

Headshot of Colin Mackay

Hi, I'm Colin. I'm a software engineer with over 30 years of experience based in central Scotland, specialising in Microsoft technologies, initially with C++ and then in C#. I was a Microsoft MVP from 2007 to 2010 and a Code Project MVP from 2005 to 2009.