Like in Lambda Expression and LINQ

2020-02-02 11:44发布

How can I do something like this:

customers.where(c=>c.Name **like** "john");

I know this isn't possible but I was wondering how can I have something similar.

标签: c# linq lambda
6条回答
Lonely孤独者°
2楼-- · 2020-02-02 11:59

Here is my code :

string s="somethings";

customers.Where(c => c.Name != null && c.Name.ToLower().Contains(s.ToLower()));

Somethings like that.

查看更多
欢心
3楼-- · 2020-02-02 12:06

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.

查看更多
时光不老,我们不散
4楼-- · 2020-02-02 12:07

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.

查看更多
Deceive 欺骗
5楼-- · 2020-02-02 12:11
using System.Data.Linq.SqlClient;
...
customers.where(c=>SqlMethods.Like(c.Name, "john"));
查看更多
戒情不戒烟
6楼-- · 2020-02-02 12:16

Use Regex.IsMatch in your where statement or for a more simpler version without wildcards etc.:

customers.where(c=>c.Name.Contains("john"));
查看更多
对你真心纯属浪费
7楼-- · 2020-02-02 12:20
customers.Where(c => c.Name.Contains("john"));
查看更多
登录 后发表回答