使用LINQ动态选择列? [英] Select a Column Dynamically using LINQ?
问题描述
所以我尝试使用 query.Select(colname)
使用扩展方法也尝试使用 Func< < / code>但我不知道如何去做这个。我已经阅读了关于linq的动态扩展以及反射,但反射到
GetValue
函数不会为数据库中的列返回值。请帮助我,我只是想在运行时动态地选择一个列,没有任何条件。
我认为最简单的是动态地构建查询。让我们假设现在所有的潜在列都有相同的类型 - 字符串。请注意,您可以通过在您选择的任何列上调用ToString()来强制执行此操作。这很重要,因为所选对象都需要相同的类型。然后使用查询条件简单地构造查询,并选择适当的列选择,使用扩展方法将其标记到查询上。
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)
{
...
}
我希望这个有创意的例子可以帮助你走上正轨。
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.
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.
这篇关于使用LINQ动态选择列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!