2012-02-14 52 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,看看它是否能解決問題。