The simple answer is “you shouldn’t”.
There is a hacky trick which allows you to do it:
var myList = new[] { new { X = (object) null, Y = (object) null } }.ToList();
myList.Clear();
foreach (object x in GetAllX())
// ...
But it would really be more reasonable to use it the way it was intended:
var myList = GetAllX().Where(x => Process(x))
.SelectMany(x => GetAllY(x).Select(y => new { X = x, Y = y }))
.ToList();
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.