DEV Community

Discussion on: Fizz Buzz in Every Language

Collapse
 
alexphi profile image
Alejandro Figueroa • Edited

Didn't see a C# solution, so here's mine (with some linq love):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FizzBuzz
{
    static class Program
    {
        static void Main(string[] args)
        {
            var buzzMap = new Dictionary<int, string>
            {
                { 3, "Fizz" },
                { 5, "Buzz" },
            };

            Func<int, string> buzzer = i =>
            {
                var buzzed = buzzMap.Keys
                    .Where(k => i % k == 0)
                    .Select(k => buzzMap[k]);

                return buzzed.Any() ? buzzed.Aggregate((prev, next) => prev += next) : null;
            };

            var output = Enumerable.Range(1, 100)
                .Select(i => buzzer(i) ?? i.ToString())
                .Aggregate(new StringBuilder(), (sb, s) => sb.AppendLine(s))
                .ToString();

            Console.WriteLine(output);
        }
    }
}