我正在尝试构建一个匿名对象数组,其中每个对象都是这样的:
new {type="internal",title="Linktitle",target="_blank",link="http://www.google.se"}
我已经声明了一个类“链接”,匿名对象应该被转换为
class Link{
public string type {get;set;}
public string target {get;set;}
public string title {get;set;}
public string link {get;set;}
}
现在我正在尝试投射对象,比如
List<Link> links = Model.relatedLinks.Select(l => new Link{type=l.type,target=l.target,title=l.title,link=l.link}).ToList();
然后我收到错误
Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
我找到了关于如何投射匿名对象的this页面,但我也是这样做的。或者我错过了什么?
答案 0 :(得分:7)
如果relatedLinks
本身是动态值,则会遇到两个问题:
Select
和ToList
方法。您可以通过强制转换lambda表达式来解决第一个问题。您可以直接致电Enumerable.Select
来解决第二个问题:
// 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();
或者为了格式化:
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();
如果Model.relatedLinks
已经IEnumerable<dynamic>
(或类似的东西),那么您可以将Select
称为扩展方法 - 但您仍然需要一个强类型的委托。例如,后一版本将成为:
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();