2012-12-13 48 views
0

這段代碼很糟糕,我只搜索一個屬性(CompanyName)。我該如何動態地編寫這個查詢,或者在任何情況下都更好?實體框架代碼第一個動態查詢

public List<SubContractor> GetSearchSubcontractorList() 
    { 
     var list = CacheObjects.Subcontractors; 
     var searchItem = string.Empty; 
     if (string.IsNullOrWhiteSpace(this.SearchCompanyName) == false) 
     { 
      var indexes = this.SearchCompanyName.IndexOfAll("*").ToList(); 
      if (indexes.Any() == false) 
      { 
       list = list.Where(x => x.CompanyName == this.SearchCompanyName).ToList(); 
      } 

      if (indexes.Count() == 1) 
      { 
       if (this.SearchCompanyName.StartsWith("*")) 
       { 
        searchItem = this.SearchCompanyName.Replace("*", string.Empty); 
        list = list.Where(x => x.CompanyName.EndsWith(searchItem)).ToList(); 
       } 
       else 
       { 
        searchItem = this.SearchCompanyName.Replace("*", string.Empty); 
        list = list.Where(x => x.CompanyName.StartsWith(searchItem)).ToList(); 
       } 
      } 

      if (indexes.Count() == 2) 
      { 
       searchItem = this.SearchCompanyName.Replace("*", string.Empty); 
       list = list.Where(x => x.CompanyName.Contains(searchItem)).ToList(); 
      } 
     } 

     return list; 
    } 

回答

1

對不起,我錯了。我編輯過,檢查出新的解決方案。我認爲你只有4種不同的情況可以測試嗎?沒有通配符,以通配符開頭,以通配符結尾,通配符結束。新的解決方案使用延遲的查詢執行,以便您可以繼續使用更多屬性構建查詢。公正的警告,仍然沒有遵守...

var filteredSubcontractors = (from s in list 
          select s); 

    if (string.IsNullOrWhiteSpace(this.SearchCompanyName) == false) 
    { 
     searchItem = this.SearchCompanyName.Replace("*", string.Empty); 

     if (!SearchCompanyName.Contains("*")) 
     { 
      filteredSubcontractors = (from s in filteredSubcontractors 
          where s.CompanyName == this.SearchCompanyName 
          select s); 
     } 
     else if(SearchCompanyName.StartsWith("*")) 
     {  
      filteredSubcontractors = (from s in filteredSubcontractors 
          where s.CompanyName.EndsWith(searchItem) 
          select s); 
     } 
     else if(SearchCompanyName.EndsWith("*")) 
     { 
      filteredSubcontractors = (from s in filteredSubcontractors 
          where s.CompanyName.StartsWith(searchItem) 
          select s); 
     } 
     else 
     { 
      filteredSubcontractors = (from s in filteredSubcontractors 
          where s.CompanyName.Contains(searchItem) 
          select s); 
     } 
    } 

    ... 
    //Repeat for as many other properties that you want to filter on 
    ... 

    //All the conditions that you added will not actually be evaluated 
    //until this line is executed. 
    var result = filteredSubcontractors.ToList(); 

    return result; 

你也可以看看這個堆棧溢出問題。在這裏有很多其他的想法(可能比我更好)。 Generating LinqToEntities Where statement depending on the user selection

+0

*是搜索的通配符。道歉,如果不明確。所以*要麼不存在,要麼在開始時,在結束時或者兩者都存在。這就是爲什麼我按照這種方式編寫代碼的原因。 – arame3333

+0

哦,明白了,看看新的答案,看看這是否更好。 –

+0

是的,雖然它不能正常工作,但它更好。我需要檢查搜索字符串是否以StartWith的條件開始並以*結尾。但是我的其他問題是,我必須爲所有其他搜索條件執行相同的代碼,例如SearchCompanyAddress。我看不到抽象這種代碼的方式,以避免重複自己。 – arame3333