代码之家  ›  专栏  ›  技术社区  ›  Scott Marlowe

linq to sql:如何编写“like”select?

  •  20
  • Scott Marlowe  · 技术社区  · 16 年前

    我有以下SQL:

    select * from transaction_log where stoptime like '%2008%'
    

    如何用linq-to-sql语法写这个?

    6 回复  |  直到 16 年前
        1
  •  30
  •   Nick Craver    16 年前

    如果要使用literal方法,则如下所示:

    var query = from l in transaction_log
                where SqlMethods.Like(l.stoptime, "%2008%")
                select l;
    

    另一个选择是:

    var query = from l in transaction_log
            where l.stoptime.Contains("2008")
            select l;
    

    如果是日期时间:

    var query = from l in transaction_log
            where l.stoptime.Year = 2008
            select l;
    

    那个方法在 系统.data.linq.sqlclient 命名空间

        2
  •  1
  •   Will    16 年前
    from x in context.Table where x.Contains("2008") select x
    
        3
  •  1
  •   Dustin Boswell    16 年前

    如果stoptime数据类型为string,则可以使用.contains()函数,也可以使用.startswith()和.endswith()。

        4
  •  0
  •   Mike Ceranski    16 年前

    如果使用contains to方法,则执行的操作类似于“%somestring%”。如果使用StartsWith方法,则它与“someString%”相同。最后,endsWith与使用“%somestring”相同。

    总而言之,contains可以在字符串中找到任何模式,但startswith和endswith可以帮助您在单词的开头和结尾找到匹配项。

        5
  •  0
  •   MADMap    16 年前

    真正有趣的一点是,.NET在Context.Table中使用“From x”时创建类似“select*from table”的查询,其中x.contains(“test”)select x”的名称类似于“%test%”,这非常令人印象深刻。

        6
  •  0
  •   Scott Marlowe    16 年前

    谢谢——回答得好。

    实际上,这是一个日期时间类型;我必须将“stoptime”类型转换为:

    var query = from p in dbTransSummary.Transaction_Logs
        where ( (DateTime) p.StopTime).Year == dtRollUpDate.Year
        select
    

    次要点。很好用!