【问题标题】:yield return foreach in linqlinq中的收益回报foreach
【发布时间】:2012-08-02 16:33:17
【问题描述】:

问题: 谁能告诉我如何在 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>”。存在显式转换(您是否缺少演员表?)

【问题讨论】:

    标签: linq foreach return yield


    【解决方案1】:

    使用Select 而不是ForEach,它会为你做yield returm

    【讨论】:

      【解决方案2】:

      您应该使用Select 而不是ForEach,它可以满足您的需求。

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

      我不确定内部的ToList 是否必要,您可以使用Cast&lt;T&gt; 而不是实现中间列表。

      【讨论】:

        猜你喜欢
        • 2010-12-21
        • 2010-11-27
        • 2011-05-27
        • 2011-01-22
        • 2012-01-14
        • 1970-01-01
        • 2018-01-23
        • 2010-12-01
        • 1970-01-01
        相关资源
        最近更新 更多