Uncategorized

FizzBuzz in one line C# Linq

The FizzBuzz problem is this:
– Print numbers from 1 to 100.
– Print “Fizz” instead of the number if the current number is evenly divisible by 3.
– Print “Buzz” instead of the number if the current number is evenly divisible by 5.
– Print “FizzBuzz” instead of the number if the current number is evenly divisible by both 3 and 5.

Here’s the FizzBuzz problem, expressed as a single line in C# using Linq:


Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine((i % 3 == 0 && i % 5 == 0) ? "FizzBuzz" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i.ToString()));

It took about 45 seconds to write the code. =]

Advertisement

One thought on “FizzBuzz in one line C# Linq

  1. Enumerable.Range(1, 100)
    .Select(a => String.Format(“{0}{1}”, a % 3 == 0 ? “Fizz” : “”, a % 5 == 0 ? “Buzz” : “”))
    .Select((b, i) => String.IsNullOrEmpty(b) ? (i + 1).ToString() : b)
    .ToList()
    .ForEach(o => Console.WriteLine(o));

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 )

Connecting to %s