2015-02-09 19 views
1

我正在用jQuery測試自動完成功能,但我無法顯示正確的標籤。當搜索只涉及1場或標準,這很簡單:在jquery自動完成與LINQ中顯示正確的標籤

var model = db.UserProfiles.Where(u => u.Department.Contains(term)) 
       .Take(10).Select(r => new 
       { 
        label = r.Department 
       }).Distinct(); 

      return Json(model, JsonRequestBehavior.AllowGet); 

但是,如果我要處理多個搜索條件(即當用戶輸入搜索關鍵詞,它會看起來無處不在表中找到匹配結果),例如:

var model = db.UserProfiles.Where(u => (u.FirstName + " " + u.LastName).Contains(term) || u.Department.Contains(term) || 
       u.JobTitle.Contains(term) || u.PhoneNumber.Contains(term) || u.Extension.Contains(term) || u.Location.Contains(term)) 
       .Take(10).Select(r => new 
       { 
        label = //How do I display the correct label here? 
       }).Distinct(); 

      return Json(model, JsonRequestBehavior.AllowGet); 

預期輸出:

如果有一個人的名字「特里」,並且也有一個表中的所謂「技術」部門,當用戶鍵入「te」,它應顯示「Technology」和「Terry」

回答

1

你應該能夠模擬在LINQ case語句使用三元的運營商,像這樣的實體:

var model = db.UserProfiles.Select(r => new 
      { 
       label = (u.FirstName + " " + u.LastName).Contains(term) ? (u.FirstName + " " + u.LastName) : 
              u.Department.Contains(term) ? u.Department : 
              u.JobTitle.Contains(term) ? u.JobTitle : 
              u.PhoneNumber.Contains(term) ? u.PhoneNumber : 
              u.Extension.Contains(term) ? u.Extension : 
              u.Location.Contains(term) ? u.Location : null 
      }).Where(l => l != null).Distinct().Take(10); 

     return Json(model, JsonRequestBehavior.AllowGet); 
1

你會使用字符串的空白列表會更好,並concating每個匹配設定一個接一個。

如果您希望使這種動態更加動態化,您可以使用使用.Concat(UserProfile類的元屬性)和反射的交互過程。

var model = (new List<string>()) 
    .Concat(db.UserProfiles 
      .Where(u => (u.FirstName + " " + u.LastName).Contains(term)) 
      .Select(u => (u.FirstName + " " + u.LastName)) 
      .Distinct()) 
    .Concat(db.UserProfiles 
      .Where(u => u.Department.Contains(term)) 
      .Select(u => u.Department) 
      .Distinct()) 
    .Concat(db.UserProfiles 
      .Where(u => u.JobTitle.Contains(term)) 
      .Select(u => u.JobTitle) 
      .Distinct()) 
    .Concat(db.UserProfiles 
      .Where(u => u.PhoneNumber.Contains(term)) 
      .Select(u => u.PhoneNumber) 
      .Distinct()) 
    .Concat(db.UserProfiles 
      .Where(u => u.Extension.Contains(term)) 
      .Select(u => u.Extension) 
      .Distinct()) 
    .Concat(db.UserProfiles 
      .Where(u => u.Location.Contains(term)) 
      .Select(u => u.Location) 
      .Distinct()) 
    .OrderBy(s => s)//must have an orderby in order to use Take 
    .Take(10) 
    .ToList(); 

return Json(model, JsonRequestBehavior.AllowGet);