shw shw - 3 months ago 8
JSON Question

return dynamic object with all child nodes as Json in - error: cannot use a lamda expression as an argument to a dynamically dispatched

I have an object that I'm returning from a third party so I need it to be dynamic (see IEnumerable requirements below). I want to return the object as Json with all of its child nodes.

I have two questions


  1. how can I do a .Select on the dynamic object (c.Nodes) (is this
    the way to go?)

  2. How can I keep looping through the nodes until it's done.



This is the code I wrote so far but now
.Select( c =>...
is giving an error


cannot use a lamda expression as an argument to a dynamically
dispatched...


IEnumerable<dynamic> requirements = _Requirements.GetRequirements();
return Json(new
{
Requirements = requirements.Select(r => new
{
r.Text,
r.Number,
nodes = r.nodes.Select(c => new
{
c.Text,
c.Number,
nodes = c.Nodes
//and overhere keep looping through the nodes until it's done
})
})
});


Thank you!

Answer

The reason you get this compile error is because your inner collection of r.node is a dynamic type and thus the extension methods can't be found for it.

Your case is similar to this question. Instead what you should do is:

nodes = ((IEnumerable<dynamic>)r.nodes)
        .Select(c => new
        {
            c.Text,
            c.Number,
            nodes = c.Nodes
        //and overhere keep looping through the nodes until it's done
    })

If you want to be sure that it won't get an exception when casting you can do r.nodes is IEnumerable<dynamic> ? /*the select*/ : Enumerable.Empty<dynamic>


For second question, if I properly understood what you meant then you can write a recursive method that gets a dynamic and then checks if it has a nodes property which is an IEnumerable<dynamic> and if so recursively calls itself foreach node in the nodes. Something along the general idea of:

public static IEnumerable<dynamic> SomeName (dynamic input)
{
    var collection = input as IEnumerable<dynamic>;
    if (collection == null)
        return Enumerable.Empty<dynamic>();

    foreach (var item in collection)
    {
        /*recursive part*/
    }

    return collection;
}

(Haven't tested - just quick concept writing)

Comments