Search code examples
c#linqprojection

Full object projection with additional values in LINQ


Is it possible to project every property of an object and add more, without specifically listing them all. For instance, instead of doing this:

   var projection = from e in context.entities
                    select new QuestionnaireVersionExtended
                    {
                        Id = e.Id,
                        Version = e.Version,
                        CreationDate = e.CreationDate,
                         ... 
                         many more properties
                         ...
                        NumberOfItems = (e.Children.Count())
                    };

Can we do something like this:

   var projection = from e in context.entities
                    select new QuestionnaireVersionExtended
                    {
                        e,
                        NumberOfItems = (e.Children.Count())
                    };

Where it will take every property from e with the same name, and add the "NumberOfItems" property onto that?


Solution

  • No this is not possible. The select clause of a LINQ expression allows for normal C# expressions which produce a value. There is no C# construct which will create an object via an object initializer in a template style manner like this. You'll need to either list the properties or use an explicit constructor.