像LINQ中的条件一样

时间:2010-09-20 14:55:37

标签: linq sql-like

我对LINQ比较陌生,不知道如何做一个Like条件。我有一个IEnumerable的myObject列表,想要做像'Help%'这样的myObject.Description。我怎么能做到这一点?感谢

4 个答案:

答案 0 :(得分:5)

看这里:

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):

自定义LIKESystem.Data.Linq.SqlClient.SqlMethods.Like):

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

答案 1 :(得分:4)

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

myObject.Description.StartsWith("Help")

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

答案 2 :(得分:2)

根据您要检查的位置,您可以使用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;

答案 3 :(得分:1)

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

相关问题