tags:

views:

51

answers:

1

Hi all I am trying to do a very simple dynamic query which will select a column dynamically I mean the selection of column would depend upon another query so I would select x col if cond1 and y if cond2 so I tried using query.Select(colname) using the extension method also tried using Func<> but I am not sure how to go about this I have read about dynamic extension for linq and also reflection but woth reflection to the GetValue function does not return value for my column in database. please help me out I am jus trying to select a column dynamically at runtime and no condtions really on it.

+2  A: 

I think the easiest thing is to simply build up your query dynamically. Let's assume for the present that all of the potential columns have the same type -- string. Note that you can force this by calling ToString() on whatever column you are selecting. This is important because the selected objects all need the same type. Then simply construct your query with the query conditions and choose the proper column selection to tag onto the query using an extension method.

 var query = db.Widgets.Where( w => w.Price > 10M );
 IEnumerable<string> display = null;
 if (likesName)
 {
    display = query.Select( w => w.Name );
 }
 else if (likesDescription)
 {
    display = query.Select( w => w.Description );
 }
 else
 {
    display = query.Select( w => w.Name + " (" + w.Description + ")" );
 }

 foreach (var item in display)
 {
     ...
 }

I hope this contrived example helps you get on the right track.

tvanfosson
Thanks it helped..
Misnomer