请问 linq 怎么动态查询多个 select、group 或 orderby?
class Employee
{
public string EmpID { get; set; }
public bool Sex { get; set; }
public int Age { get; set; }
}
假设有下面2个变量:
int groupIndex
List<Employee> emps
现在要根据 groupIndex 取值来生成不同的 SQL 语句,如果直接写 SQL 语句话可以把一条语句拆分成多个字符串来组合想要的结果,
但是用 linq 的话需要要写多次:
if (groupIndex == 1)
{
var dataSource =
from e in emps
group e by new { e.EmpID } into g
orderby new { g.Key.EmpID }
select new { g.Key.EmpID };
}
else if (groupIndex == 2)
{
var dataSource =
from e in emps
group e by new { e.EmpID, e.Sex } into g
orderby new { g.Key.EmpID, g.Key.Sex }
select new { g.Key.EmpID, g.Key.Sex };
}
else if (groupIndex == 3)
{
var dataSource =
from e in emps
group e by new { e.EmpID, e.Sex ,e.Age } into g
orderby new { g.Key.EmpID, g.Key.Sex, e.Age }
select new { g.Key.EmpID, g.Key.Sex, e.Age };
}
else ..................
有没有办法用动态查询来实现呢?我看到 MSDN 里面的例子有办法用目录树组合查询,但是没有多个 select、group或orderby 这样的例子,请问谁知道怎么做?
------解决方案--------------------
here's the link: http://talentgrouplabs.com/blog/archive/2007/11/25/dynamic-linq-queries--dynamic-where-clause-part-1.aspx
C# code
string[] searchTerms = new string[] { "Maria", "Pedro" };
string search = "";
foreach (string searchTerm in searchTerms)
{
search += "ContactName.Contains(\""+searchTerm+"\") or ";
}
search += "1=0";
var query = db.Customers.Where(search).Select(c => c);
------解决方案--------------------
楼主别忘了把答案贴上来啊,让我们也学习学习,谢谢
------解决方案--------------------
对LINQ还不是很熟练
------解决方案--------------------
能不能把查寻条件写到Linq语句中,Linq语句应该可以相当之复杂和嵌套的啊,我觉得.