2012-02-14 54 views
5

我试图通过linq投影将List<Topic>转换为匿名或动态类型...我正在使用下面的代码,但它似乎并没有正常工作。它返回的动态类型没有错误,但是,如果我尝试枚举儿童场(list<object/topic>),那么它说列表<T> LINQ投影到匿名或动态类型

结果查看=类型'<>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; 
} 

我做的是扁平化自包含对象的列表 - 本质上这是一个将被装进一个树型视图(jstree)波苏斯名单。

的主题类定义为:

public class Topic 
{ 
    public Guid Id {get;set;} 
    public string Name {get;set;} 
    public List<Topic> Children {get;set;} 
} 

这里是什么样的返回动态对象的第一个成员看起来像一个例子:

[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> 
      >} 
} 
+3

你打电话FlattenTopics?匿名类型不能跨程序集使用:http://stackoverflow.com/questions/2993200/return-consume-dynamic-anonymous-type-across-assembly-boundaries – 2012-02-14 21:37:21

+0

LINQ结果不适用范围,由于匿名类型:http://msdn.microsoft.com/en-us/magazine/ee336312.aspx – 2012-02-14 21:44:51

+0

@Igor - 否 - 从我的MVC控制器中的Action方法... – bbqchickenrobot 2012-02-14 22:09:19

回答

0

这是正确的方式 - 已经加载到一个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(); 
     }; 
0

为什么你有相同的LINQ代码两次?在定义_Flatten函数后,您可以立即调用它 - var topics = _Flatten(Repository.Query<Topic>().ToList()

看起来你正在创建两个相同的匿名类型,一个在_Flatten func里面,一个在它外面。我认为编译器足够聪明来处理这个问题,但试着改变你的调用来明确使用_Flatten,看看它是否能解决问题。