2009-08-07 88 views
0

我有一個LINQ查詢,它在多個字段中搜索字符串(使用正則表達式)。我想根據在哪個字段中找到文本來對結果進行排序。按搜索條件排序C#LINQ

目前我有這樣的:

var results = from i in passwordData.Tables["PasswordValue"].AsEnumerable() 
      where r.IsMatch(i.Field<String>("Key").Replace(" ","")) || 
      r.IsMatch(i.Field<String>("Username").Replace(" ","")) || 
      r.IsMatch(i.Field<String>("Other").Replace(" ","")) 
      orderby i.Field<String>("Key"), 
      i.Field<String>("Other"), 
      i.Field<String>("Username") 
      select i; 

我想重點首先找到匹配,那麼匹配等發現,然後匹配用戶名找到。如果可能的話,匹配鍵和其他匹配的匹配應該在匹配唯一鍵的匹配之前。

我現在有各種各樣的基於關鍵第一,因此,如果匹配上的其他發現,但主要與A開始的代碼,它會在關鍵找到匹配的,其中主要有Z.

開始前進行排序

在此先感謝,這不是一個很難回答的問題,但我不知道如何做到這一點,因爲我是LINQ的新手。

回答

7

使用let關鍵字來捕獲中間值,您可以輕鬆地排序是否有匹配之前您排序的匹配值:

var results = from i in passwordData.Tables["PasswordValue"].AsEnumerable() 
       let fields = new { 
        Key = i.Field<String>("Key"), 
        Username = i.Field<String>("Username"), 
        Other = i.Field<String>("Other") } 
       let matches = new { 
        Key = r.IsMatch(fields.Key.Replace(" ","")), 
        Username = r.IsMatch(fields.Username.Replace(" ","")), 
        Other = r.IsMatch(fields.Other.Replace(" ","")) } 
       where matches.Key || matches.Username || matches.Other 
       orderby matches.Key descending, fields.Key, 
       matches.Username descending, fields.Username, 
       matches.Other descending, fields.Other 
       select i; 
+0

非常感謝,這個工作! – Ruud 2009-08-08 16:50:10

0

您唯一的解決方法是創建2個方法,一個用於密鑰搜索,另一個用於其他搜索。然後根據哪個字段在搜索結果中被擊中,然後按順序運行。雖然這可能是額外的編碼,但它是唯一的辦法,我看到它與完成創建自己的表達樹很難。

0

下面是一個簡單的,但次優高性能,辦法做到這一點:

static IEnumerable<DataRow> DoSearch(DataTable table, RegEx r, string fieldName) { 
    return table.AsEnumerble() 
       .Where(row => r.IsMatch(row.Field<string>(fieldName).Replace(" ", "")) 
       .OrderBy(row => row.Field<string>(fieldName)); 

} 

var table = passwordData.Tables["PasswordValue"]; 
var results = DoSearch(table, r, "Key") 
    .Union(DoSearch(table, r, "Username") 
    .Union(DoSearch(table, r, "Other"); 

Union方法會過濾掉重複的情況下,連續多個字段匹配。