我有一個基本的搜索控件,根據預定義的搜索/過濾標準,通過下拉列表從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