我正在尝试List<Topic>通过linq投影将a转换为匿名或动态类型...我正在使用以下代码,但它似乎无法正常工作.它返回动态类型而没有错误,但是,如果我尝试枚举子字段(list<object/topic>)然后它说
结果视图=
'<>f__AnonymousType6<id,title,children>'"MyWebCore.dll"和"MvcExtensions.dll"中都存在类型
奇怪.
这是我正在使用的代码:
protected dynamic FlattenTopics()
{
Func<List<Topic>, object> _Flatten = null; // satisfy recursion re-use
_Flatten = (topList) =>
{
if (topList == null) return null;
var projection = from tops in topList
select new
{
id = tops.Id,
title = tops.Name,
children = _Flatten(childs.Children.ToList<Topic>())
};
dynamic transformed = projection;
return transformed;
};
var topics = from tops in Repository.Query<Topic>().ToList()
select new
{
id = tops.Id,
title = tops.Name,
children = _Flatten(tops.Children.ToList<Topic>())
};
return topics;
}
Run Code Online (Sandbox Code Playgroud)
我正在做的就是压缩一个包含自包含对象的列表 - 基本上它是一个POCO列表,它将被填充到树视图(jstree)中.
Topic类定义为:
public class Topic
{
public Guid Id {get;set;}
public string Name {get;set;}
public List<Topic> Children {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
以下是返回的动态对象的第一个成员的示例:
[0] = {
id = {566697be-b336-42bc-9549-9feb0022f348},
title = "AUTO",
children = {System.Linq.Enumerable.SelectManyIterator
<MyWeb.Models.Topic,
MyWeb.Models.Topic,
<>f__AnonymousType6<System.Guid,string,object>
>}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法 - 必须加载到 DTO / POCO 并返回:
_Flatten = (topList) =>
{
if (topList == null) return null;
var projection = from tops in topList
//from childs in tops.Children
select new JsTreeJsonNode
{
//id = tops.Id.ToString(),
data = tops.Name,
attr = setAttributes(tops.Id.ToString(), tops.URI),
state = "closed",
children = _Flatten(tops.Children)
};
return projection.ToList();
};
Run Code Online (Sandbox Code Playgroud)