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 10 apps Authentication automation azure Azure AD Azure Functions Azure OpenAI best practices c# C# 14 caching Cloud Architecture cloud computing clustering code data Development devops javascript kubernetes LangChain machine learning mediapipe microservices Monitoring nginx node.js nodejs performance Performance Optimization production Programming rate limiting Redis Security Serverless software software engineering System System Design tweaks ubuntu UML

Written by:

377 Posts

View All Posts
Follow Me :

Leave a Reply

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