As a condition in LINQ

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

+4
source share
4 answers

Look at here:

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

Excerpt:

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; 
+5
source

Usually you use the same syntax that you would use outside the query.

 myObject.Description.StartsWith("Help") 

Regardless of whether it actually works, it depends on where you use LINQ (it can be run as code, in which case everything works or is converted to something like another, like SQL, which may have limitations), but it always worth a try.

+4
source

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

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

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

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

If you want to make case insensitive, you should use IndexOf :

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

you can use the string.StartsWith or string.EndsWith or string.Contains property to use it like Like Operator.

Startswith will work as "A%"
Endswith will work as "% A"
Contains will work as "% A%"

+1
source

All Articles