Error when trying to cast anonymous object, Razor

前提是你 提交于 2019-12-04 19:58:23

If relatedLinks itself is a dynamic value, you've got two problems:

  • The lambda expression part as already reported
  • Extension methods can't be called on dynamic values (as extension methods). This affects both the Select and ToList methods.

You can work round the first by casting the lambda expression. You can work round the second by calling Enumerable.Select directly:

// Note: don't use var here. We need the implicit conversion from
// dynamic
IEnumerable<Link> query = Enumerable.Select(Model.relatedLinks, 
                              (Func<dynamic, Link>) (l => new Link { 
                                                            type = l.type,
                                                            target = l.target,
                                                            title = l.title,
                                                            link = l.link } );
var links = query.ToList();

Or for the sake of formatting:

Func<dynamic, Link> projection = l => new Link { 
                                        type = l.type,
                                        target = l.target,
                                        title = l.title,
                                        link = l.link };
IEnumerable<Link> query = Enumerable.Select(Model.relatedLinks, projection);
var links = query.ToList();

If Model.relatedLinks is already IEnumerable<dynamic> (or something similar) then you can call Select as an extension method instead - but you still need to have a strongly-typed delegate. So for example, the latter version would become:

Func<dynamic, Link> projection = l => new Link { 
                                        type = l.type,
                                        target = l.target,
                                        title = l.title,
                                        link = l.link };
IEnumerable<Link> query = Model.relatedLinks.Select(projection);
var links = query.ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!