I’ve got a generic<> function that takes a linq query (‘items’) and enumerates through it adding additional properties. How can I select all the properties of the original ‘item’ rather than the item itself (as the code below does)?
So equivalent to the sql: select *, ‘bar’ as Foo from items
foreach (var item in items) { var newItem = new { item, // I'd like just the properties here, not the 'item' object! Foo = 'bar' }; newItems.Add(newItem); }
There’s no easy way of doing what you’re suggesting, as all types in C# are strong-typed, even the anonymous ones like you’re using. However it’s not impossible to pull it off. To do it you would have to utilize reflection and emit your own assembly in memory, adding a new module and type that contains the specific properties you want. It’s possible to obtain a list of properties from your anonymous item using: