views:

83

answers:

2

Hi,

I often need to augment a object with a property for instance. Until now (tired of it ;) and it's ugly too) I have done it this way:

var someListOfObjects = ...;

var objectsWithMyProperty = from o in someListOfObjects
                            select new
                            {
                                o.Name,    /* Just copying all the attributes I need */
                                o.Address, /* which may be all of them. */

                                SomeNewProperty = value
                            };

Is there a clever way to do this? What I have done previously is something like this:

var objectsWithMyProperty = from o in someListOfObjects
                            select new
                            {
                                OldObject = o,           /* I access all of the old properties from here */    
                                SomeNewProperty = value
                            };

I guess this could be done with some reflection, but I imagine there is a faster approach which makes something equivalent to the first cumbersome approach.

Thanks, Lasse

+4  A: 

No there is no support for appending new properties to an existing anonymous type. An anonymous type expression can only be used to create a brand new anonymous type with the specified properties. The two best alternatives for appending new properties are the ones listed in the question.

JaredPar
That's too bad :( Thanks... :)
lasseespeholt
+1  A: 

I think what you are looking for is something like the ExpandoObject that was added in C# 4.0 along with the dynamic type

http://msdn.microsoft.com/en-us/magazine/ff796227.aspx

Internally it uses a dictionary so you can add/remove members dynamically. The first time you try to access a property like:

obj.NewProperty = newValue

the ExpandoObject will automatically add this to its internal dictionary.

Hope this helps.

Roly
Now you mention the `ExpandoObject` I recall that I have the magazine you link to. I would have preferred a static solution but a dynamic is better than none :) Thanks...
lasseespeholt