2009-05-22 52 views
4

我正在嘗試使用webservice和Linq To Sql來訪問數據庫進行自動完成搜索。Linq To Sql搜索多列和多個字

這是我的代碼。這將返回匹配任何搜索詞的結果,我想對其進行修改,以便每個結果都包含所有搜索詞。

我知道SQL全文搜索可能是最優雅的解決方案,但我想看看如果這個功能是可能的而不修改數據庫。

string[] searchTerms = searchString.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToArray(); 
     IQueryable<AccountResult> results = db.cdAccounts 
      .Select(x => 
       new AccountResult() 
       { 
        idAccount = x.id_Account, 
        AccountName = x.AccountNme, 
        AccountNumber = x.AccountNum 
       }).Distinct().OrderBy(x => x.AccountName); 
     foreach (string searchTerm in searchTerms) 
      results = results.Where(x => x.AccountName.Contains(searchTerm) || x.AccountNumber.Contains(searchTerm)); 

     return results.OrderBy(x => x.AccountName).Take(40).ToList(); 
+0

我想的比理想的解決方案更小,現在我使用LINQ搜索該第一檢索詞過去的方法中,如果有多於1個搜索術語,我使用從DB和過濾器的初步結果結果不符合第二,第三等條款。它有點醜陋,但它足夠快。仍然接受建議。 – KClough 2009-05-22 14:11:13

回答

1

我結束了使用linq來搜索第一個術語,然後如果有多個術語。我願意改進/優化。

//... 
if (searchTerms.Count() > 1) 
{ 
    List<string> remainingSearchTerms = new List<string>(); 
    for (int x = 1; x < searchTerms.Count(); x++) 
     remainingSearchTerms.Add(searchTerms[x]); 
    List<SearchResult> matchingResults = new List<SearchResult>(); 

    foreach (SearchResult result in allResults) 
     if (MatchSearchTerms(new string[] { result.Name, result.Number, result.id.ToString() }, remainingSearchTerms.ToArray())) 
      matchingResults.Add(result); 

    return matchingResults.OrderBy(x => x.Name).Take(MaxResults).ToList(); 
} 
else 
    return allResults.OrderBy(x => x.Name).Take(MaxResults).ToList(); 
//... 

private bool MatchSearchTerms(string[] searchFields, string[] searchTerms) 
{ 
    bool match = true; 
    foreach (string searchTerm in searchTerms) 
    { 
     if (match) 
     { 
      bool fieldMatch = false; 
      foreach (string field in searchFields) 
      { 
       if (field.ToLower().Contains(searchTerm.ToLower())) 
       { 
        fieldMatch = true; //Only one field needs to match the term 
        break; 
       } 
      } 
      match = fieldMatch; 
     } 
     else 
      break; 
    } 
    return match; 
} 
0

我不知道LINQ到SQL,但它看起來像你重新分配結果在你的每個循環,當你應該追加到結果。

+0

我正在嘗試篩選結果。 僞代碼: 第一個循環: Results.Where x包含 '123' 二次迴路 結果(其中X包含 '123')(當X含有 '456') 這是否有意義? – KClough 2009-05-22 13:25:43