I wish to construct a list of anonymous types constructed by iterating through two other lists in a nested loop.
var myList = new List<???>();
foreach (object x in GetAllX())
{
if (Process(x))
{
foreach (object y in GetAllY(x))
{
myList.Add(new {
X = x,
Y = y
});
}
}
}
I know that I can construct a List of anonymous types using ToList(), (see this question), but I can’t see how I can use this in the above case.
Note that I can’t change the GetAllX and GetAllY methods.
The simple answer is “you shouldn’t”.
There is a hacky trick which allows you to do it:
But it would really be more reasonable to use it the way it was intended:
If you really can’t use this pure-functional style for some reason, or you find you have to instantiate such a list in multiple places, you should probably declare a normal class instead of using an anonymous type. Remember that anonymous types are compiled into classes anyway, so there is no performance benefit to anonymous types, and even the readability/maintainability benefit is questionable if you have to resort to tricks like the hacky one at the top of this post.
Some people suggest to use
List<dynamic>, but I recommend against it. It severely hampers maintainability because the property names and types are no longer checked at compile-time (you could mistype one and get a run-time bug); it slows down run-time performance because every access goes through the dynamic dispatcher; and also, once you put your objects into this list, you are basically stuck with them being dynamic, because you can’t cast them back to the anonymous type.