【问题标题】:SQL LIKE Equivalent in C#C# 中的 SQL LIKE 等效项
【发布时间】:2015-04-14 23:41:11
【问题描述】:

我的问题使用以下代码 -

string searchString = dropdownlist.SelectedValue;

List objects = (from o in Object.List()
                       where dropdownlist.SelectedIndex <= 0 || 
                           o.CustomField.Contains(searchString)
                       orderby o.Date descending
                       select order).ToList();

我遇到的情况如下 - 下拉列表中的项目是通用消息,例如“客户'{0}'有'{1}'订单”。在对象方面,o.CustomField 看起来像“客户 'Bob' 有 '5' 个订单”。显然,这意味着

o.CustomField.Contains(searchString)

不会返回任何东西。我一直在研究通配符,但未能成功返回。这就是我尝试设置通配符的方法:

searchString = dropdownlist.SelectedValue.Replace("{0}", "*").Replace("{1}", "*");

我想知道是否有比坐下来解析 '{' 或 '}' 之间的所有不同子字符串更简洁的方法。

【问题讨论】:

  • 所以,为了清楚起见,您希望将字符串:Customer '{0}' has '{1}' orders 与:Customer * has * orders 匹配?
  • 正确,这就是我想要的。
  • 研究使用正则表达式。这是一笔不小的投资,但它会有所回报。

标签: c# linq wildcard sql-like


【解决方案1】:

您可以通过使用正则表达式来实现您的目标。请参阅 Regex.Match 方法。 您可以将下拉列表中选择的字符串转换为正则表达式,然后在 LINQ 查询中使用 Match 方法。

Regex r = new Regex(String.Format ("Customer {0} has {1} orders", "([^\s]+)",  "([^\s]+)"));

这段代码:

o.CustomField.Contains(searchString)

然后可以改为:

r.Match(o.CustomField).Success

【讨论】:

  • 这在 LINQ 上不起作用
  • @Chesare 通过打开一个新问题提供一些示例代码。回到这里并指出新问题。
  • 此代码导致错误“LINQ to Entities no reconoce el método 'System.Text.RegularExpressions.Match Match(System.String)'”: Regex r = new Regex("HR\\d{4}"); var q = from eq in db.CataEquiposRenta where r.Match(eq.NUMEROINTERNO).Success select new { eq.IDEQUIPO, Number = eq.NUMEROINTERNO.Substring(2) };
  • 此代码(使用SqlFunctions.PatIndex)工作正常:// Formato de numero interno: HR1234 var query = from eq in db.CataEquiposRenta where SqlFunctions.PatIndex("HR[0-9][0-9][0-9][0-9]%", eq.NUMEROINTERNO) == 1 orderby eq.NUMEROINTERNO descending select new { eq.IDEQUIPO, Number = eq.NUMEROINTERNO.TrimEnd().Substring(2) };
【解决方案2】:

试试here提到的方法 或者使用field.StartsWith("Customers") &amp;&amp; field.EndsWith("orders") &amp;&amp; field.Contains("has")的组合

【讨论】:

    【解决方案3】:

    只需在{\d+} 上执行Regex.Replace,将其替换为*

    类似:

    string s = Regex.Replace(input, @"{\d+}", "*");
    

    【讨论】:

    • 谢谢,自从上面的评论中提到了正则表达式以来,我一直在做更多的调查,我认为这最适合我希望做的事情。谢谢!
    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2013-03-20
    • 1970-01-01
    • 2012-07-31
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多