tags:

views:

64

answers:

2

I have a table with 40 (int) columns and I need to get certain columns depending on user input, sometimes it might be 1 and some other times it might be all 40, how can I do this using LINQ?

A: 

How many rows is it? It might be simpler to just always fetch all 40 columns and then just ignore the values that you don't need. If that will give performance problems then you can use the Select extension to select the columns you want:

IQueryable<MyResult> myResult;
if (wantColumnFoo) {
    myResult = table.Select(x => new MyResult { x.Id, Foo = x.Foo });
} else {
    myResult = table.Select(x => new MyResult { x.Id, Foo = null });
}

But that will soon be a lot of work if you need to handle all 40 columns like this.

Mark Byers
Not a great idea, bringing back data you don't need and then have to post-query process it...
OMG Ponies
I think you misunderstood. The first example brings back too much data but does not do any processing - simply ignore the fields you don't need. The second example does not bring back too much data. The query is automagically optimized by Linq.
Mark Byers