yield return foreach在LINQ中的含义

4
问题: 有没有人可以告诉我如何在LINQ中返回值。 我想返回一组RadToolBarButtons,并在创建它们的同时分配它们的值。
代码: 我尝试了两种方法:
IEnumerable<RadToolBarButton> collection = ContextMenuColumn.ToList()
      .ForEach(x => yield return new RadToolBarButton() { Value = x });

错误 11 无法隐式将类型 'void' 转换为 'System.Collections.Generic.IEnumerable'

IEnumerable<RadToolBarButton> collection =
    ContextMenuColumn.SelectMany<string,IEnumerable<RadToolBarButton>>(
       x => new RadToolBarButton() { Value = x });

错误 11:无法隐式将类型 'Telerik.Web.UI.RadToolBarButton' 转换为 'System.Collections.Generic.IEnumerable>'。存在显式转换(是否缺少强制转换?)

2个回答

7

你应该使用Select而不是ForEach,它可以完成你想要的操作。

IEnumerable<RadToolBarButton> collection = ContextMenuColumn.ToList()
  .Select(x => new RadToolBarButton { Value = x });

我不确定内部的 ToList 是否必要,你可以尝试使用 Cast<T> 而不是 实例化 中间列表。


2

使用 Select 替换 ForEach,这样它会为你执行 yield return


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接