views:

673

answers:

3

Is there a way to add a property to the objects of a Linq query result other than the following?

var query = from x in db.Courses
                select new
                {
                    x.OldProperty1,
                    x.OldProperty2,
                    x.OldProperty3,
                    NewProperty = true
                };

I want to do this without listing out all of the current properties of my object. There are many properties, and I don't want to have to update this code whenever I may change my class.

I am still learning with LINQ and I appreciate your suggestions.

+5  A: 

I suppose you could return a new object composed of the new property and the selected object, like:

var query = from x in db.Courses
                select new
                {
                    Course x,
                    NewProperty = true
                };
Eric King
I was really looking more for a way to "inject" the property into my current object. But thanks!
Ronnie Overby
+4  A: 

eking's answer will be the most straightforward approach.

If that doesn't work for you (because you need to pass the results around or whatever), and assuming the class you're dealing with already defines the property you want to set, you could create a copy constructor or factory method that takes an existing instance plus the value of the property you want to set:

var query = from x in db.Courses
            select new Course(x, valueOfNewProperty);

Alternatively, if Course doesn't define the property, you could subclass it and use the same approach:

var query = from x in db.Courses
            select new CourseWithExtraProperty(x, valueOfNewProperty);

(obviously, pick a better name for your subclass)

Again, though, unless you really need to do this, stick with eking's solution.

John Price
+5  A: 

Add it with partial classes:

public partial class Courses
{
    public String NewProperty { get; set; }
}

Then you can assign it after you've created the object.

weiran
That's compile time. Isn't the question asking for run time, thus making this not a valid answer to the question?
peSHIr
no this is a fine answer.
Ronnie Overby
Of course, if you're going to alter the original class design (to make it a partial), you might as well just go ahead and add the property...
Eric King
The class is generated by LINQ to SQL. This is the way to do it. I don't know why I didn't think to do this! I have done this before. I think it's called a brain fart.
Ronnie Overby
Yes, in that case I'd go with weiran's suggestion.
Eric King