List < T & gt; LINQ Projection to Anonymous or Dynamic Type

advertisements

I'm trying to convert a List<Topic> to an anonymous or dynamic type via linq projection... I'm am using the following code, but it doesn't seem to work properly. It returns the dynamic type without error, however, if I try to enumerate the children field (list<object/topic>) then it says

Results View = The type '<>f__AnonymousType6<id,title,children>' exists in both 'MyWebCore.dll' and 'MvcExtensions.dll'

Strange.

Here is the code I am using:

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

All i'm doing is flattening a list of self containing objects - basically it's a list of POCOs that will be stuffed into a tree view (jstree).

The Topic class is defined as:

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

And here is an example of what the first member of the returned dynamic object looks like:

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


Why do you have the same LINQ code twice? After you define your _Flatten func, you can just call it immediately - var topics = _Flatten(Repository.Query<Topic>().ToList().

It looks like you're creating two identical anonymous types, one inside the _Flatten func and one outside it. I would think the compiler is smart enough to handle that, but try changing your call to explicitly use _Flatten, see if it solves the problem.