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:
- public IEnumerable<int> FetchValuesLessThanTen(List<int> source)
- {
- foreach(var item in source)
- {
- if (item < 10)
- yield return item;
- }
- }
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<>.