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
If you're happy with an array, you can use an array initializer:
var items = new[] {
new { Foo = "def" },
new { Foo = "ghi" },
new { Foo = "jkl" }
};
You can then call ToList()
if you want to get a List<T>
out. Marc's solution will be slightly more efficient than calling ToList()
due to not needing the extra copying, but I think I'd probably use the "array and then ToList()" solution in most cases as there's less clutter. Of course, if performance is crucial for that bit of code, it changes things.
EDIT: As you're iterating over a collection, just use Select
:
var anonymousItems = items.Select (item => new { Foo=item.Foo,
Bar=item.Other })
.ToList();