【问题标题】:Sort by search criteria C# LINQ按搜索条件排序 C# LINQ
【发布时间】:2009-08-07 19:48:00
【问题描述】:

我有一个 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;

我希望首先在 Key 中找到匹配项,然后在 Other 中找到匹配项,然后在 Username 中找到匹配项。如果可能,同时匹配 Key 和 Other 的匹配项应先于仅匹配 Key 的匹配项。

我目前的代码首先基于 Key 进行排序,因此如果在 Other 上找到匹配但 Key 以 A 开头,它将在 Key 以 Z 开头的 Key 上找到匹配之前排序。

提前谢谢,我认为这不是一个很难的问题,但我只是不知道如何做到这一点,因为我是 LINQ 的新手。

【问题讨论】:

    标签: c# linq sorting


    【解决方案1】:

    使用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】:

      您的一个解决方案是创建 2 种方法,一种用于 Key 搜索,另一种用于 Other 搜索。然后根据您运行订单的搜索中的哪个字段。虽然这可能是额外的编码,但这是我看到它完成的唯一方法,而无需创建自己的表达式树,这要困难得多。

      【讨论】:

        【解决方案3】:

        这是一种简单但性能欠佳的方法:

        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 方法将在一行匹配多个字段的情况下过滤掉重复项。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-03
          • 1970-01-01
          • 2018-06-29
          • 1970-01-01
          • 1970-01-01
          • 2012-02-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多