如何返回 IEnumerable如果有一个收益,则收集
如果我想返回输入集合,在迭代器块中使用 return 语句而不是 foreach 的最明智的方法是什么?
public IEnumerable<T> Filter(IEnumerable<T> collection)
{
if (someCondition)
{
// return collection; - cannot be used because of "yield" bellow
foreach (T obj in collection)
{
yield return obj;
}
yield break;
}
yield return new T();
}
What is the smartest way to use return statement in iterator block instead of foreach if I want to return input collection?
public IEnumerable<T> Filter(IEnumerable<T> collection)
{
if (someCondition)
{
// return collection; - cannot be used because of "yield" bellow
foreach (T obj in collection)
{
yield return obj;
}
yield break;
}
yield return new T();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,我可能会这样做:
在更复杂的情况下,某些集合可以选择包含在返回值中,我使用
Union
。In this case, I would probably do:
In more complex cases, where some collections are optionally included in the return value, I use
Union
.恐怕这就是你在迭代器块中所能做的全部事情。 F# 中没有与
yield!
相当的东西,也没有yield foreach
的概念。不幸的是,但事实就是这样:(当然,您可以首先避免使用迭代器块:
或者如果您有更复杂的逻辑:
I'm afraid that's all you can do within an iterator block. There's no equivalent of
yield!
in F#, or the idea of ayield foreach
. It's unfortunate, but that's the way it is :(Of course, you could avoid using an iterator block in the first place:
Or if you have more complex logic: