Tuesday, 27 October 2020

C# -Yield return in C#

 using System;

using System.Collections.Generic;

class Program
{
    private static IEnumerable<string_plants = new[] { "Apple""Pear""Sunflower""Carrot" };

    static void Main(string[] args)
    {
        Console.WriteLine("Classic:");
        foreach(var fruit in GetFruits())
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("\r\nYield return:");
        foreach (var fruit in GetFruitsWithYield())
        {
            Console.WriteLine(fruit);
        }
    }

    private static IEnumerable<stringGetFruits()
    {
        var result = new List<string>();

        foreach(var plant in _plants)
        {
            if(plant == "Apple" || plant == "Pear")
            {
                result.Add(plant);
            }
        }

        return result;
    }

    private static IEnumerable<stringGetFruitsWithYield()
    {
        foreach (var plant in _plants)
        {
            if (plant == "Apple" || plant == "Pear")
            {
                yield return plant;
            }
        }
    }
}

No comments:

Post a Comment