Iterating through an anonymous variable in a different scope than where it was created.
I am writing a unit test for an mvc web app that checks that the returned list of anonymous variables (in jsonresult) is correct. so I need to iterate over this list, but I can't find a way to do it.
so I have 2 methods
1) returns json result. This json result has a property called data. this property has an object of type, but inside it there is a list of anonymous variables
2) the method calls method 1 and checks if the returned jsonresult is satisfied.
if i run the test and i break the debugger i can hover over the result and see the items in it. I just don't find a way to do it in code. (just using foreach is not possible because at the point I need I am not in the method that created the anonymous method)
I think you mean "anonymous type" wherever you say "anonymous variable", but you can still foreach
iterate over the list with by simply declaring the iteration variable as a type object
:
foreach (object o in myList)
{
// Not sure what you're actually trying to do in here...
}
If you need to validate the content, you can use the fact that anonymous types are overridden in a ToString
useful way. Your test can check the result of projecting each item onto a line. Indeed, you can easily convert your result object to a sequence of strings:
var strings = ((IEnumerable) result).Cast<object>.Select(x => x.ToString());
Then check strings
, perhaps using SequenceEqual
.
source to share
ok i found this thanks for part of your solution :) apparently i can convert it to IEnumerable and then i can iterate through the results. THH!
var objects= ((IEnumerable)result.Data);
foreach (object obj in objects)
{
//inhere i can use reflection to get the properties out of it
}