FizzBuzz using C# yield

Yield.
Yield has two great uses,
a. It helps to provide custom iteration without creating temp collections.
b. It helps to do state-full iteration.

[TestClass]
public class FizzBuzzTest
{
    [TestMethod]
    public void Test1()
    {
        var iEnumerableString = new FizzBuzz().GenerateFizzBuzzUpto(100);
        var list = iEnumerableString.ToList();
        Assert.IsTrue(list[0] == "Fizz:3");
        Assert.IsTrue(list[1] == "Buzz:5");
        Assert.IsTrue(list[6] == "FizzBuzz:15");
    }
}
public class FizzBuzz
{
    public IEnumerable<string> GenerateFizzBuzzUpto(int numberUpto)
    {
        for (var counter = 1; counter < numberUpto; counter++)
        {
            if (counter%3 == 0 && counter%5 == 0)
            {
                yield return $"FizzBuzz:{counter}";
            }
            if (counter % 3 == 0)
            {
                yield return $"Fizz:{counter}";
            }
            if (counter % 5 == 0)
            {
                yield return $"Buzz:{counter}";
            }
        }
    }
}

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.