繁体   English   中英

名单 <T> LINQ Projection to Anonymous或Dynamic类型

[英]List<T> LINQ Projection to Anonymous or Dynamic type

我正在尝试通过linq投影将List<Topic>转换为匿名或动态类型...我正在使用以下代码,但它似乎无法正常工作。 它返回动态类型而没有错误,但是,如果我尝试枚举子字段( list<object/topic> ),那么它说

结果视图='MyWebCore.dll'和'MvcExtensions.dll'中存在类型'<>f__AnonymousType6<id,title,children>' '

奇怪。

这是我正在使用的代码:

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;
}

我正在做的就是压缩一个包含自包含对象的列表 - 基本上它是一个POCO列表,它将被填充到树视图(jstree)中。

Topic类定义为:

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>
          >} 
 }

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

看起来你正在创建两个相同的匿名类型,一个在_Flatten func中,一个在它外面。 我认为编译器足够智能来处理它,但尝试更改您的调用以显式使用_Flatten,看看它是否解决了问题。

这是正确的方法 - 必须加载到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();
        };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM