No Need for Temporary Collections, Yield Might Help ✅
Normally when we need to fetch the items from a collection we might create a Temporary List to hold the retrieved items and return. 🌀
Following is the C# code using the temporary list :
➖➖➖➖➖➖➖
To avoid the usage of this temporary collection you could choose to use the yield. 🔥
It will yield the result as and when the result set is enumerated.
Below is the code using the yield keyword :
〰〰〰〰〰〰
#CSharp #Collections
@ProgrammingTip
Normally when we need to fetch the items from a collection we might create a Temporary List to hold the retrieved items and return. 🌀
Following is the C# code using the temporary list :
public List<int> GetValuesGreaterThan100
(List<int> masterCollection)
{
List<int> tempResult = new List<int>();
foreach (var value in masterCollection)
{
if (value > 100)
tempResult.Add(value);
}
return tempResult;
}
➖➖➖➖➖➖➖
To avoid the usage of this temporary collection you could choose to use the yield. 🔥
It will yield the result as and when the result set is enumerated.
Below is the code using the yield keyword :
public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection)
{
foreach (var value in masterCollection)
{
if (value > 100)
yield return value;
}
}
〰〰〰〰〰〰
#CSharp #Collections
@ProgrammingTip
You may be wondering why the Entity Framework team chose to call the method Remove rather than Delete, and for that matter, why they choose Add instead of Insert. 🤷🏿♂️
The names were chosen for consistency with other collections and sets in the .NET Framework.
Other collections all use the Add/Remove pair of methods to bring elements into and out of the collection.
〰〰〰〰〰〰
#EF #Collections
@ProgrammingTip
The names were chosen for consistency with other collections and sets in the .NET Framework.
Other collections all use the Add/Remove pair of methods to bring elements into and out of the collection.
〰〰〰〰〰〰
#EF #Collections
@ProgrammingTip