I've got a method that returns an array, the type of which I have stored in a Type object further up. The code I have for this is thus:
Type StoryType = Type.GetType("my.ns.Story");
Type StoryTypeArray = Type.GetType("my.ns.Story[]");
object stories = SomeMethodInfo.Invoke(BigFatObject,some_params);
In this example, I know stories is of type StoryTypeArray
, and what I really want to do is something like:
foreach (Story instance in stories) { ... }
However, I can't figure out how to turn the object stories
into something I can loop through and pull data out of.
Any ideas?
To iterate through an array of objects in JavaScript, you can use the forEach() method aong with the for...in loop. The outer forEach() loop is used to iterate through the objects array. We then use the for...in loop to iterate through the properties of an individual object. ✌️ Like this article?
In c#, the Foreach loop is useful to loop through each item in an array or collection object to execute the block of statements repeatedly. Generally, in c# Foreach loop will work with the collection objects such as an array, list, etc., to execute the block of statements for each element in the array or collection.
It's not clear from your question if the Story
type is actually known to you at compile time. If it is, the solution is trivial; just cast stores
to Story[]
and iterate over it as usual:
foreach(Story instance in (Story[])stories) { ... }
This also means that StoryType
can be written as typeof(Story)
and StoryTypeArray
can be written as typeof(StoryTypeArray[])
instead of using the less-safe Type.GetType
that you're using.
If the type is not actually known to you at compile time, then you won't be able to write foreach(Story instance...
, since that won't be a valid type. If you just want to iterate over the array, then you can do this:
foreach(object item in (Array)stories) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With