2013-10-11 70 views
0

我正在Intranet網站上運行一個簡單的搜索,我想根據查詢的相關性對結果進行排序。使用linq的相關性排序結果

這是我到目前爲止。

var customer = from c in db.Customer 
       select c; 

if (!String.IsNullOrEmpty(searchString)) 
{ 
    customer = customer.Where(c => SqlFunctions.StringConvert((double)c.CustomerID).Trim().Equals(searchString) 
    || c.CustomerName.ToUpper().Contains(searchString.ToUpper()) 
    || SqlFunctions.SoundCode(c.CustomerName.ToUpper()) == SqlFunctions.SoundCode(searchString.ToUpper())); 
} 

switch (s) 
{ 
    case "NameDesc": 
     customer = customer.OrderByDescending(c => c.CustomerName); 
     break; 
    default: 
     customer = customer.OrderBy(c => c.CustomerName); 
     break; 
} 

由於我使用聽起來像在返回額外的可能的匹配,這對我來說是有用的,但我想最匹配什麼已經鍵入搜索框首先出現在結果中。

這是可能對OrderBy使用查詢嗎?還是我需要使用全文搜索?

回答

0

嘗試增加權重參數的查詢:

customersLevel1 = customer 
.Where(c => SqlFunctions.StringConvert((double)c.CustomerID).Trim().Equals(searchString)) 
.Select(c => new { cust = c, weight = 1}); 

customersLevel2 = customer 
.Where(c => c.CustomerName.ToUpper().Contains(searchString.ToUpper())) 
.Select(c => new { cust = c, weight = 2}); 

customersLevel3 = customer 
.Where(c => SqlFunctions.SoundCode(c.CustomerName.ToUpper()) == SqlFunctions.SoundCode(searchString.ToUpper())) 
.Select(c => new { cust = c, weight = 3}); 

然後檢索與一個查詢的數據到數據庫,你可以使用聯盟():

var result = (customersLevel1) 
      .Union(customersLevel2) 
      .Union(customersLevel3) 
      .OrderBy(c => c.weight) 
      .Select(c => c.cust);