问题
Hi all I am trying to do a very simple dynamic query which will select a column dynamically i.e. selection of column would depend upon another query.So, I would select col X if condition 1 and Y if condition 2.
So I tried using query.Select(colname) using the extension method also tried using Func<> but I am not sure how to go about doing this. I have read about dynamic extension for linq and also reflection but with reflection to the GetValue function does not return value for my column in database. Please help me out I am just trying to select a column dynamically at runtime and no conditions really on it.
回答1:
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.
来源:https://stackoverflow.com/questions/2717039/select-a-column-dynamically-using-linq