views:

106

answers:

4

Lets say we have an expression:

var prices = from p in PriceDB.Prices
             where p.TypeID == 12
             orderby p.PriceType.Title
             select p;

Is it possible to modify the select list?

I imagine it looking something like this:

var newPriceList = prices.Select( p => p.ExchangeRate );

This may be an odd request, but in my code (which is too long and complex to post here) I want to conditionally add fields to be output depending on a CheckBoxList.

I assume, of course, that I'm trying to go about this the wrong way...

Thanks,

Matt.

A: 

You might want to look at this http://stackoverflow.com/questions/114029/dynamic-linq-and-dynamic-lambda-expressions

Or the Dynamic Expression API (System.Linq.Dynamic).

Martin Ingvar Kofoed Jensen
A: 

While you could go down the dynamic route, I would strongly consider not doing so. What is the cost of fetching the extra values if you don't need them, in your particular case? Is the problem that they're being displayed dynamically and you only want them displayed in certain cases? If so, I'd suggest modifying the display code somehow.

It's hard to stay strongly typed (which has various advantages) while being dynamic in terms of what you fetch. Of course, if you always want to fetch the same "shape" of data (e.g. always just a decimal value from each row) then that's reasonably easy - let me know if that's something you'd like to see demonstrated.

If you could tell us more about your problem, we may be able to suggest alternative solutions.

Jon Skeet
For a 100 column table, reading redundant values means unnecessary network IO. Plus it can also affect query execution plan.
Hasan Khan
@Hasan: Sure, that's why I asked what the cost is. We certainly don't know that the table has 100 columns at the moment.
Jon Skeet
A: 

If I understood you correct this is explaining how to build dynamic queries:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

lasseespeholt
A: 

I imagine it looking something like this:

Actually it would look exactly like that. First, build a query, selecting the entire record. Then add a select (using the Select() method seem the easiest way) to limit the selection. Linq-to-Sql will sort out the two selects, and use the proper reselt, so theres just one select in the final SQL.

There's no really good way to choose between multiple selects. I would probably use a switch/case.

James Curran
Did you remove your code sample?
Matt W
No. The first line is a quote from the OP, and refers to code there.
James Curran