我有一个基本的搜索控件,根据预定义的搜索/过滤标准,通过下拉列表从CRM中列出公司。每个DropDown的默认选择是“ALL”,否则用户选择一个特定的项目。我希望能够基于选择动态地构建一个Linq查询。在5个选择器中,他们提供了可以匹配公司表的值,但是其中两个选择器(如果选择了其中一个或两个)将需要一个连接或连接,否则不应再次执行基本结果集的操作。我希望这是有道理的。添加条件动态加入Linq
我不知道如何有效地做到这一点。这里是我的代码:
private void Search()
{
EnergyPubsCRMDataContext dc = new EnergyPubsCRMDataContext();
var results = (from c in dc.Companies
select c);
//only create the join if the selected index > 0
if (ddlIndustry.SelectedIndex > 0)
{
//A company can be in 1 or more industries, thus here I want to join
//with the CompanyIndustry table and have a WHERE clause to match on the ddlIndustry.SelectedValue
}
//only create the join if the selected index > 0
if (ddlServices.SelectedIndex > 0)
{
//A company can offer 1 or more services. Here I want to join to the CompanyService table
//on the CompanyID and have a WHERE clause to match the ddlServices.SelectedValue
}
//These work OK to shape the overal query further (they don't need joins)
if (ddlCountry.SelectedIndex > 0)
results = results.Where(c => c.CountryID == Convert.ToInt32(ddlCountry.SelectedValue));
if (ddlStateRegion.SelectedIndex > 0)
results = results.Where(c => c.StateRegionID == Convert.ToInt32(ddlStateRegion.SelectedValue));
if (ddlAccountManagers.SelectedIndex > 0)
{
Guid g = new Guid(ddlAccountManagers.SelectedValue);
results = results.Where(c => c.UserId == g);
}
results = results.OrderBy(c => c.CompanyName);
//Bind to Grid....
}
我不知道,但也许这可以将您指向正确的方向:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – Jeroen 2010-08-20 20:43:00