Tuesday, 13 September 2016

c# - Is yield useful outside of LINQ?



When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding because I feel the overhead of maintaining the state of the yeilding method doesn't buy me much. In almost all cases where I am returning a collection I feel that 90% of the time, the calling method will be iterating over all elements in the collection, or will be seeking a series of elements throughout the entire collection.




I do understand its usefulness in linq, but I feel that only the linq team is writing such complex queriable objects that yield is useful.



Has anyone written anything like or not like linq where yield was useful?


Answer



I recently had to make a representation of mathematical expressions in the form of an Expression class. When evaluating the expression I have to traverse the tree structure with a post-order treewalk. To achieve this I implemented IEnumerable like this:



public IEnumerator> GetEnumerator()
{
if (IsLeaf)

{
yield return this;
}
else
{
foreach (Expression expr in LeftExpression)
{
yield return expr;
}
foreach (Expression expr in RightExpression)

{
yield return expr;
}
yield return this;
}
}


Then I can simply use a foreach to traverse the expression. You can also add a Property to change the traversal algorithm as needed.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...