2012-06-13 144 views
3

假设我有一个字符串列表,像构建LINQ查询动态

list<string> cols = {"id", "name", "position"}. 

是动态生成的列表,每一个在此列表中表示数据库表中的列名。

我想要做的是动态创建一个linq查询,它只返回这些列。

var q = from e in employ 
     select new { 
      id = id, 
      name = name, 
      position = position 
}; 

如何根据输入列表生成类似的查询?

+0

Dynamic Linq http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query- library.aspx可以做到这一点 – Chocoboboy

回答

0

正如Chocoboboy所说,System.Linq.Dynamic会有所帮助。不幸的是,这并不包含在.NET框架中,但您可以从Scott Guthrie的博客下载它。 在你的情况下,你需要调用Select(string selector)(列列表硬编码或从列表中获取)。或者,我的例子包括动态Where条款(Where("salary >= 50")):

List<string> cols = new List<string>(new [] { "id", "name", "position" }); 
var employ = new[] { new { id = 1, name = "A", position = "Manager", salary = 100 }, 
    new { id = 2, name = "B", position = "Dev", salary = 50 }, 
    new { id = 3, name = "C", position = "Secretary", salary = 25 } 
}; 
string colString = "new (id as id, name as name, position as position)"; 
//string colString = "new (" + (from i in cols select i + " as " + i).Aggregate((r, i) => r + ", " + i) + ")"; 
var q = employ.AsQueryable().Where("salary >= 50").Select(colString); 
foreach (dynamic e in q) 
    Console.WriteLine(string.Format("{0}, {1}, {2}", e.id, e.name, e.position)); 

然而,这种方法在某种程度上违背了LINQ的强类型查询的目的,所以我会谨慎使用。