【问题标题】:Like condition in LINQLINQ 中的类似条件
【发布时间】:2010-09-20 14:55:37
【问题描述】:

我对 LINQ 比较陌生,不知道如何执行 Like 条件。我有一个 myObject 的 IEnumerable 列表,并且想要执行类似 myObject.Description 之类的操作,例如“Help%”。我怎样才能做到这一点?谢谢

【问题讨论】:

标签: linq sql-like


【解决方案1】:

看这里:

http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx

片段:

StartsWithContains

var query = from c in ctx.Customers
            where c.City.StartsWith("L") && c.City.Contains("n")
            select c;

如果您应该将它与 LINQ to SQL 一起使用(不适用于 LINQ to Objects):

自定义LIKE (System.Data.Linq.SqlClient.SqlMethods.Like):

var query = from c in ctx.Customers
            where SqlMethods.Like(c.City, "L_n%")
            select c;

【讨论】:

    【解决方案2】:

    您通常使用与在查询之外使用的完全相同的语法。

    myObject.Description.StartsWith("Help")
    

    这是否真的有效取决于您使用 LINQ 的位置(它可能作为代码运行,在这种情况下一切正常,或者转换为其他类似的东西,例如 SQL,这可能有限制),但是,但总是值得一试。

    【讨论】:

      【解决方案3】:

      您可以使用StartsWithEndsWithContains,具体取决于您要检查的位置:

      var result = from o in myCollection
                   where o.Description.StartsWith("Help")
                   select o;
      

      您可以选择传递 StringComparison 来指定是否忽略大小写(对于 StartsWithEndsWith),这将使操作的行为更像 SQL 查询:

      var result =
          from o in myCollection
          where o.Description
              .StartsWith("Help", StringComparison.InvariantCultureIgnoreCase))
          select o;
      

      如果你想做一个不区分大小写的包含,你需要使用IndexOf来代替:

      var result = 
          from o in myCollection
          where o.Description
              .IndexOf("Help", StringComparison.InvariantCultureIgnoreCase) > 0
          select o;
      

      【讨论】:

      • StartsWith和朋友也让你指定比较类型。
      【解决方案4】:

      您可以使用字符串的 string.StartsWithstring.EndsWithstring.Contains 属性将其用作 Like 运算符。
      Startswith 适用于 Like 'A%'
      Endswith 适用于 Like '%A'
      包含将像“%A%”一样工作

      【讨论】:

        猜你喜欢
        • 2013-08-22
        • 2011-04-16
        • 2020-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-23
        相关资源
        最近更新 更多