代码之家  ›  专栏  ›  技术社区  ›  Ruud

按搜索条件C Linq排序

  •  0
  • Ruud  · 技术社区  · 17 年前

    我有一个LINQ查询,它在多个字段中搜索一个字符串(使用regex)。我想根据在哪个字段中找到文本对结果进行排序。

    目前我有:

    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开头的匹配项上找到匹配项之前排序。

    提前谢谢,我想这不是一个困难的问题,但我只是不知道怎么做,因为我是新来的林肯。

    3 回复  |  直到 17 年前
        1
  •  7
  •   dahlbyk    17 年前

    使用 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;
    
        2
  •  0
  •   RC1140    17 年前

    您的一个解决方案是创建两个方法,一个用于键搜索,另一个用于其他搜索。然后根据您运行订单时在seach上点击的字段。虽然这可能是额外的编码,但我认为这是唯一一种可以完成的方法,即创建自己的expresion树,而这非常困难。

        3
  •  0
  •   SLaks    17 年前

    下面是一个简单但性能次优的方法:

    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 方法将在行与多个字段匹配时筛选出重复项。