Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
动态构建linq查询_Linq - Fatal编程技术网

动态构建linq查询

动态构建linq查询,linq,Linq,假设我有一个字符串列表,比如 list<string> cols = {"id", "name", "position"}. 如何根据输入列列表生成这样的查询?正如Chocoboboy所说,System.Linq.Dynamic会有所帮助。不幸的是,.NET framework中没有包含此功能,但您可以从Scott Guthrie的博客下载它。 在您的情况下,需要调用Select(字符串选择器)(列列表硬编码或来源于列表)。或者,我的示例包括一个动态Where子句(Where(“s

假设我有一个字符串列表,比如

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

如何根据输入列列表生成这样的查询?

正如Chocoboboy所说,
System.Linq.Dynamic
会有所帮助。不幸的是,.NET framework中没有包含此功能,但您可以从Scott Guthrie的博客下载它。 在您的情况下,需要调用
Select(字符串选择器)
(列列表硬编码或来源于列表)。或者,我的示例包括一个动态
Where
子句(
Where(“salary>=50”)
):

List cols=新列表(新[]{“id”、“name”、“position”});
var employ=new[]{new{id=1,name=“A”,position=“Manager”,salary=100},
新的{id=2,name=“B”,position=“Dev”,salary=50},
新{id=3,name=“C”,position=“Secretary”,salary=25}
};
string colString=“新建(id作为id,名称作为名称,位置作为位置)”;
//string colString=“新建(“+(从cols中的i选择i+”作为“+i”)。聚合((r,i)=>r+”,“+i)+”);
var q=employ.AsQueryable().Where(“salary>=50”).Select(colString);
foreach(q中的动态e)
WriteLine(string.Format(“{0},{1},{2}”,e.id,e.name,e.position));

但是,这种方法在某种程度上违背了LINQ强类型查询的目的,因此我会谨慎使用。

您可以使用表达式树来构建动态LINQ查询。 下面是一个示例:

动态Linq可以做到这一点
var q = from e in employ
        select new {
          id = id,
          name = name,
          position = position
};
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));