How to read properties of anonymous types using a "dynamic" variable

I had a tricky idea of ​​using a dynamic variable to check the results of a method that returns an anonymous type - more precisely, it returns a JsonResult, which, like json, looks like

{ "newData" : [ 1120741.2697475906, 826527.64681837813 ], "oldData" : [ 1849870.2326665826, 1763440.5884212805 ], "timeSteps" : [ 0, 4.8828124999999998e-10 ], "total" : 2 } 

I can read JSonResult which will give me an anonymous type. Here is my code:

 var jsonResult = controller.GetChangeData(1) as JsonResult; dynamic data = jsonResult.Data; Assert.AreEqual(2, data.total); // This works fine :) 

But how do I get, for example, in "newData"? This code is ....

 var newData = data.newData; 

Gives me System.Linq.Enumerable.WhereSelectArrayIterator, but I do not know what to do with it in order to be able to use it as a double digit.

I tried to make it as double [], but it does not work either.

As an aside, can I easily check if a property is defined in a dynamic?

+4
source share
3 answers

The reason .ToArray() does not work is because the extension method and extension methods are not available at run time. It just means that you have to call the function statically. Does Enumerable.ToArray<double>(data.newData) ?

You might need Enumerable.ToArray(Enumerable.Cast<double>(data.newData)) depending on which newData elements have.

+3
source

To get instance properties of a dynamic type

 PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dyn); foreach (PropertyDescriptor prop in props) { object val = prop.GetValue(dyn); var propName = prop.Name; var propValue = val; } 

where dyn is an instance of a dynamic object.

+2
source

Can I use the JavaScriptSerializer class to parse a Json string in a dynamic variable? For instance:

 var serializer = new JavaScriptSerializer(); var jsonObj = serializer.Deserialize<dynamic>(jsonString); var newData1 = jsonObj["newData"][0]; 
+1
source

All Articles