views:

80

answers:

3

I am relatively new to LINQ and don't know how to do a Like condition. I have an IEnumerable list of myObject and want to do something like myObject.Description like 'Help%'. How can I accomplish this? Thanks

+2  A: 

You can use StartsWith, EndsWith, or Contains depending where you want to check:

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

You can optionally pass a StringComparison to specify whether to ignore case or not (for StartsWith and EndsWith) which would make the operation behave more like a SQL query:

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

If you want to do a case insensitive contains, you need to use IndexOf instead:

var result = 
    from o in myCollection
    where o.Description
        .IndexOf("Help", StringComparison.InvariantCultureIgnoreCase) > 0
    select o;
Justin Niessner
`StartsWith` and friends also let you specify the comparison type.
Matti Virkkunen
@Matti - I mention that right after the first code example.
Justin Niessner
@Justin: Oh... er, good point! Carry on.
Matti Virkkunen
+4  A: 

You generally use the exact same syntax you'd use outside a query.

myObject.Description.StartsWith("Help")

Whether this actually works depends on where you're using LINQ (it might either be ran as code, in which case everything works, or get converted to something like else, such as SQL, which might have limitations), though, but it's always worth a try.

Matti Virkkunen
+4  A: 

Look here:

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

Snippet:

StartsWith and Contains:

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

And if you should use it with LINQ to SQL (does not work with LINQ to Objects):

Custom LIKE (System.Data.Linq.SqlClient.SqlMethods.Like):

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