How many times we declare a simple class or struct to hold a few properties only to use them only one time when returned by a method. Way too many times I think, thankfully we always have anonymous objects which can be declared in place at run time.
With that thought in mind I would like to know how I can declare one array of such anonymous objects.
Example:
var Employee = new { ID = 5, Name= "Prashant" };
This created a anonymous object with two properties, one being integer and another string.
All good here, but how should I declare a array of this kind of object, and how would you recommend iterating through it with both a for and foreach loops.
The foreach loop is really the problem I think, because foreach loops expect a declared type. Still there might be a away, if there is I would to know it too of course.
[edit – updated to show population, basic enumeration, etc]
As @Eve says, LINQ is your friend here; as a general rule of thumb, don’t try passing anonymous types around – you can, if you’re clever – but it’s a HUGE pain in the butt to deal with them outside of the context/scope they were declared.
To whit, I decided to see in what ways one could “declare an array of an anonymous type” as a fun thought experiment, and came up with these:
(note: the “Dump” is due to this being written in LINQPad)