【发布时间】:2016-06-24 02:48:17
【问题描述】:
是否可以在ForEach 方法中使用yield 内联?
private static IEnumerable<string> DoStuff(string Input)
{
List<string> sResult = GetData(Input);
sResult.ForEach(x => DoStuff(x));
//does not work
sResult.ForEach(item => yield return item;);
//does work
foreach(string item in sResult) yield return item;
}
如果没有,是否有它不起作用的原因?
【问题讨论】:
-
首先,为什么使用这种语法而不是
.Select(x=>DoStuff(x))?其次,ForEach不返回结果,因此尝试使用return或yield返回内容是无效的 -
@PanagiotisKanavos
Select不能与递归方法结合使用 -
@fubo 实际上,您可以找到使其工作的方法。您会发现许多示例展示了如何使用 LINQ 行走树木。至少您可以使用
.Concat组合递归结果,然后从选择返回结果。不过,尝试在 Action 中使用yield是完全无效的。 -
看起来您想要做的是类似于
foreach(var item in GetData(Input)) { foreach(var sub in DoStuff(item)){ yield return sub; } yield return item;}或者您可能希望在sub项目之前产生item。