如何在运行时从文本构建LINQ查询? [英] How to build a LINQ query from text at runtime?
问题描述
我有一个
class A {
public int X;
public double Y;
public string Z;
// and more fields/properties ...
};
和List<A> data
,并且可以构建linq查询,例如
and a List<A> data
and can build a linq query like e.g.
var q = from a in data where a.X > 20 select new {a.Y, a.Z};
然后dataGridView1.DataSource = q.ToList();
在我的DataGridView中显示选择.
Then dataGridView1.DataSource = q.ToList();
displays the selection in my DataGridView.
现在是一个问题,是否可以根据用户在运行时输入的文本来构建查询?喜欢
Now the question, is it possible to build the query from a text the user has entered at runtime? Like
var q = QueryFromText("from a in data where a.X > 20 select new {a.Y, a.Z}");
关键是用户(具有编程技能)可以动态自由地选择显示的数据.
The point being, that the user (having programming skills) can dynamically and freely select the displayed data.
推荐答案
好,您可以使用 Snippy 作为示例.在这种情况下,您需要使用一种接受名为data
的List<A>
的方法来编译用户代码.我的经验是,它可以正常工作,但是可能有点不对劲,特别是在添加适当的引用等方面.
Well, you can use CSharpCodeProvider
to compile code at execution time. Have a look at Snippy for an example of this. In this case you'd need to compile the user code in a method which accepts a List<A>
called data
. My experience is that it works, but it can be slightly fiddly to get right - particularly in terms of adding the appropriate references etc.
这篇关于如何在运行时从文本构建LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!