【问题标题】:Why is this Aggregate not working?为什么这个聚合不起作用?
【发布时间】:2013-10-21 05:50:54
【问题描述】:

我有Post 和许多Tags,我在其中选择了那个标签Name。我只想将所有标签输出为简单的字符串。

我收到这些错误

无法将 lambda 表达式转换为委托类型“System.Func”,因为块中的某些返回类型不能隐式转换为委托返回类型

无法将类型“int”隐式转换为“char”。存在显式转换(您是否缺少演员表?)

var posts = _db.Posts.OrderByDescending(x => x.CreatedDateTime).AsEnumerable().Select(post => new
{
    post.Id,
    post.Title,
    Tags = post.Tags.SelectMany(x => x.Name).Aggregate((current, next) => current + ',' + next) // error
});

我也尝试使用" ",甚至将分隔符存储在变量中,但没有任何帮助。我在这里做错了什么?

【问题讨论】:

  • @pasty 喜欢这样吗? post.Tags.SelectMany(x => x.Name).Aggregate((current, next) => string.Format("{0} {1}", current, next)) 没有任何变化,我得到同样的错误。
  • 是的,但这没有意义 - 抱歉,我走错了路。

标签: c# linq


【解决方案1】:

将您的SelectMany 替换为Select

【讨论】:

    【解决方案2】:

    SelectMany 会展平返回列表列表的查询,它就像一个连接快捷方式,因此您会收到错误消息。您需要做的就是用 Select 替换它,这是代码,它应该可以工作:

    var posts = _db.Posts.OrderByDescending(x => x.CreatedDateTime).AsEnumerable().Select(post => new
    {
        post.Id,
        post.Title,
        Tags = post.Tags.Select(x => x.Name).Aggregate((current, next) => current + ',' + next) // error
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 2011-04-06
      • 2013-03-10
      • 1970-01-01
      相关资源
      最近更新 更多