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 AKS algorithm algorithms API apps Authentication azure Azure AD Azure Container Apps Azure Container Instances Azure Functions c# C# 14 caching CI/CD Classification Cloud Architecture cloud computing code data Development devops information javascript kubernetes LangChain machine learning microsoft Monitoring node.js performance Performance Optimization Programming properties rate limiting Security Serverless software Software development software engineering sql System tweaks