Saturday, January 12, 2019

Yield Keyword in C#

Introduction:-
Dear friend in this article I will teach you how to use Yield  C-Sharp .

Use Of Yield:-
The main use of yield in C#

  • Custom iteration without temporary collection 
  • Stateful  iteration 
Custom Iteration :-
If I have list object i want to filter this object without using temp object so go with yield.

Ex: 1 to 5 number in list object .
Now i want to filter it if number is grater then 3


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

namespace CSharpLearnig
{
    class Program
    {
        List<int> listObj = null;
        static void Main(string[] args)
        {
            Program obj = new Program();

            // load data in listObj 
            obj.loadData();
            // Custom Iteration 
            foreach (var item in obj.listFilter())
            {
                Console.WriteLine("{0} is grater then 3.",item);
            }
            Console.ReadLine();
        }

        private IEnumerable<int> listFilter()
        {
            foreach (var item in listObj)
            {
                if (item > 3)
                    yield return item; 
            }
        }

        private void loadData()
        {
            listObj = new List<int>() { 1, 2, 3, 4, 5 };
        }
    }
}

Output:
4 is grater then 3.
5 is grater then 3.










Stateful Iteration Exaample:-

I have number list object but I want running total of this object so in this scenario by using yield you can achieve this.
1 -> 1
2 -> 3
3 -> 6
4 -> 10
5 -> 15
like this .

using System;
using System.Collections.Generic;

namespace CSharpLearnig
{
    class Program
    {
        List<int> listObj = null;
        static void Main(string[] args)
        {
            Program obj = new Program();

            // load data in listObj
            obj.loadData();
            // Runing Total by using Statefull Iteration
            foreach (var item in obj.listFilter())
            {
                Console.WriteLine("{0}",item);
            }
            Console.ReadLine();
        }
        private IEnumerable<int> listFilter()
        {
            int sum = 0;
            foreach (var item in listObj)
            {
                sum += item;
                    yield return sum;
            }
        }
        private void loadData()
        {
            listObj = new List<int>() { 1, 2, 3, 4, 5 };
        }
    }
}
Output-











Thank for giving your valuable time .

No comments:

Post a Comment