Reputation: 8237
How can I do something like this using Expression trees :
customers.Where(c => c.Name **like** "john");
I know this isn't possible but I was wondering how can I have something similar.
Note : I'm NOT looking for solutions using SQL related LINQ queries (like Linq to SQL or Linq to entities)
Upvotes: 47
Views: 87313
Reputation: 122
You can try this:
customers.where(c=>EF.Functions.Like(c.Name,"%john%");
I did a test to see the generated sql and this was the result
sql = _context.ProdutoPortfolio.Take(10).Where(c => c.NomeProduto.Contains(c.NomeProduto))
sql2 = _context.ProdutoPortfolio.Take(10).Where(c => EF.Functions.Like(c.NomeProduto, $"%{search}%")
Result sql1: If you use contains this is the result
DECLARE @__p_0 int = 10;
DECLARE @__search_1 varchar(350) = 'a';
SELECT [t].[ProductID], [t].[Cod], [t].[ProductName], [t].[SubThemeName], [t].[ThemeName]
FROM (
SELECT TOP(@__p_0) [p].[ProductID], [p].[Cod], [p].[ProductName], [p].[SubThemeName], [p].[ThemeName]
FROM [ProductPortfolio] AS [p]
) AS [t]
WHERE (@__search_1 LIKE '') OR (CHARINDEX(@__search_1, [t].[productName]) > 0)
Result sql2:
DECLARE @__p_0 int = 10;
DECLARE @__Format_2 varchar(350) = '%a%';
SELECT [t].[ProductID], [t].[Cod], [t].[ProductName], [t].[SubThemeName], [t].[ThemeName]
FROM (
SELECT TOP(@__p_0) [p].[ProductID], [p].[Cod], [p].[ProductName], [p].[SubThemeName], [p].[ThemeName]
FROM [ProductPortfolio] AS [p]
) AS [t]
WHERE [t].[productname] LIKE @__Format_2
SQL2 meets what I want, SQL2 wins
Upvotes: -1
Reputation: 440
Here is my code :
string s="somethings";
customers.Where(c => c.Name != null && c.Name.ToLower().Contains(s.ToLower()));
Somethings like that.
Upvotes: 1
Reputation: 35751
If you are targeting LINQ to SQL, use SqlMethods.Like:
customers.Where(c => SqlMethods.Like(c.Name, "%john%"));
Explanation:
The compiler will generate an expression tree from the statement above. Since LIKE
is a SQL specific construct and not common to all LINQ Query providers, the SqlMethods
class and its members are used as a "hint" for the expression compiler (compiles expression trees to SQL) to emit a LIKE
statement.
Upvotes: 31
Reputation: 128377
The first thought that comes to mind is Regex.IsMatch
.
This would come closest to providing the kind of functionality you get from LIKE
; for instance with it you could do this:
var matches = people.Where(p => Regex.IsMatch(p.Name, "A.*[mn]"));
foreach (Person match in matches)
{
Console.WriteLine(match.Name);
}
And get output like this:
Adam Aaron Aidan
Going with string.Contains
as others have suggested is almost certainly preferable if your intention is simply to look for a specific substring within Name
.
Upvotes: 10
Reputation: 51
using System.Data.Linq.SqlClient;
...
customers.where(c=>SqlMethods.Like(c.Name, "john"));
Upvotes: 5
Reputation: 49639
Use Regex.IsMatch
in your where statement or for a more simpler version without wildcards etc.:
customers.where(c=>c.Name.Contains("john"));
Upvotes: 3