动态构建LINQ查询

3
假设我有一个字符串列表,类似于:
list<string> cols = {"id", "name", "position"}.

这个列表是动态生成的,其中每个项目代表数据库表中的一个列名。
我想要做的是动态创建一个linq查询,只返回这些列。
var q = from e in employ
        select new {
          id = id,
          name = name,
          position = position
};

如何基于输入的列列表生成类似的查询?

动态 Linq 可以做到这一点。http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx - Chocoboboy
2个回答

0

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强类型查询的目的,因此我建议谨慎使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接