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. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

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