Ehsan Ghanbari

Experience, DotNet, Solutions

Use yield instead of populating a temporary list

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)



            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<>.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in MVC4
How to use PagedList In MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in MVC
comments powered by Disqus