产量在LINQ之外有用吗? [英] Is yield useful outside of LINQ?

查看:75
本文介绍了产量在LINQ之外有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我认为可以使用yield关键字时,我都会退后一步,看看它会如何影响我的项目。我总是最终返回一个集合而不是返回yeilding,因为我觉得维持yeilding方法状态的开销并不能给我带来多少好处。在几乎所有要返回集合的情况下,我都觉得90%的情况下,调用方法将遍历集合中的所有元素,或者在整个集合中寻找一系列元素。

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.

我确实了解它在linq中的用处,但我感到只有linq团队在编写如此复杂的,可查询的对象,以使yield有用。

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.

有人在收益率有用的地方写过类似linq的东西吗?

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

推荐答案

我最近不得不以Expression类的形式表示数学表达式。在评估表达式时,我必须使用后顺序树遍历遍历树结构。为了实现这一点,我实现了IEnumerable< T>。像这样:

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<T> like this:

public IEnumerator<Expression<T>> GetEnumerator()
{
    if (IsLeaf)
    {
        yield return this;
    }
    else
    {
        foreach (Expression<T> expr in LeftExpression)
        {
            yield return expr;
        }
        foreach (Expression<T> expr in RightExpression)
        {
            yield return expr;
        }
        yield return this;
    }
}

然后我可以简单地使用foreach遍历表达式。您还可以添加属性以根据需要更改遍历算法。

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

这篇关于产量在LINQ之外有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆