Blog

Filter posts by the Tags of Blog section!

Use yield instead of populating a temporary list Monday, 16 February 2015

In C# programming language, to fetch an item from a list or collection, there are some ways. Most of the developers forget to use yield keyword and they create a list and populate it based on a needed condition in the simplest possible form. Look at the following sample of populating a list in order to fetch some integer values:

 public List<int> FetchValuesLessThanTen(List<int> source)

        {

            var finalList = new List<int>();

            foreach(var item in source)

            {

                if (item < 10)

                    finalList.Add(item);

            }

            return finalList;

        }

So, it works! But in order to achieve a better performance, C# provides you yield keyword:

  1.  public IEnumerable<int> FetchValuesLessThanTen(List<int> source)
  2.         {
  3.             foreach(var item in source)
  4.             {
  5.                 if (item < 10)
  6.                     yield return item;
  7.             }
  8.         }

 

Just note, as you see, I used  IEnumerable<int> as the output of the method because the List<int> is not an iterator interface type, and the body of the method not can be iterator block. So we have to change the output of the method to IEnumerable<>.

Tags: C#

comments powered by Disqus