.Net, Programming

Use of yield in C#

Normally, when we need to fetch the items from a collection we might create a temporary list to hold the retrieved items and return. But the use of yield, we can get a collection without the use of the temporary collection.
Following is the simple example to retrieve list using return a temporary list.

public List<int> GetValuesGreaterThan50(List<int> Collection)
{
List<int> templist = new List<int>();

foreach (var value in Collection)
{
if (value > 50)
templist.Add(value);
}
return templist;
}

Here tmplist is used to store values that we want to return but we have a better and faster way to get the result by use of yield keyword so no need for temporary collections.

public IEnumerable<int> GetValuesGreaterThan50(List<int> Collection)
{
foreach (var value in Collection)
{
if (value > 50)
yield return value;
}
}

Yield returns Enumerable value as a result set so we can use it in LINQ query to get result easily. The yield keyword effectively creates a lazy enumeration over collection items that can be much more efficient. For example, if your foreach loop iterates over just the first 50 items of 1 million items, then that’s all yield returns, and you didn’t build up a collection of 1 million items internally first. Likewise, you will want to use yield with IEnumerable return values in your own programming scenarios to achieve the same efficiencies.

Tagged

Leave a Reply

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