Select a Column Dynamically using LINQ?

六月ゝ 毕业季﹏ 提交于 2019-12-11 07:26:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!