MikeTWebb
MikeTWebb

Reputation: 9279

Like condition in LINQ

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

Upvotes: 4

Views: 4607

Answers (4)

Daxesh Vora
Daxesh Vora

Reputation: 619

you can use string.StartsWith or string.EndsWith or string.Contains property of string to use it as Like Operator.
Startswith will work for Like 'A%'
Endswith will work for Like '%A'
Contains will work like '%A%'

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245499

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;

Upvotes: 2

Lasse Espeholt
Lasse Espeholt

Reputation: 17792

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;

Upvotes: 5

Matti Virkkunen
Matti Virkkunen

Reputation: 65166

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.

Upvotes: 5

Related Questions