How to avoid Temporary Collections in C# using “yield”

How to avoid Temporary Collections in C# using “yield”

Most of us do some common type of mistakes by introducing a temporary collections of any List or IEnumerable types, right? Often we do some stuffs to solve some problems in a collection, without caring about memory because it is quite easy to use and understand. But, well there is another way to do it without introducing the temporary table which is also readable and understandable. I have the code below that will clear your mind, so that you use yield instead of creating some temporary lists.

Before

public List<int> GreaterThan10(List<int> someCollection)
{
   List<int> tempResult = new List<int>();
   foreach(var value in someCollection)
   {
      if (value > 10)
       temp result.Add(value);
   }
   return temp result;
}

After

public IEnumerable<int> GreaterThan10(List<int> someCollection)
{
    foreach (var value in someCollection)
    {
       if (value > 10)
          yield return value;
    }
}

Interesting, right?

What does yield do here? Click here to go to official Microsoft Docs

Copied the remarks from Microsoft Document, So that you dont have to go to the link and read those all.
You use a yield return statement to return each element one at a time.
The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

.net .net core algorithm algorithms analysis apps azure Blogging c# canvas cloud computing code computer data Development devops docker excel framework git github Given goal html5 information Input javascript kubernetes microsoft nature Process model project properties requirements servers software software engineering sql System tweaks users version virtualization virtual machine Visual Studio 2012

Leave a Reply

Your email address will not be published. Required fields are marked *