I am looking for best practices for creating collections made from anonymous types.
There are several approaches - this one and most answers on this thread assume th
One option is to use an example item to create the collection via generic type inference, for example:
static List CreateEmptyList(T template) {
return new List();
}
void Foo() {
var list = CreateEmptyList(new { Foo = "abc" });
list.Add(new { Foo = "def" });
//...
}
You can also do this without creating an instance (but using an anonymous method that never gets caller), but I don't think it saves anything really... we might not create an instance of the object, but we do create an instance of a delegate, so not much of a saving...
You also mention sorting the data; see the reply here for a way to use List
with a lambda, and hence with anonymous types - i.e.
list.Sort(x=>x.Foo);