正则表达式在LINQ查询中的应用

huangapple go评论60阅读模式
英文:

Regex in LINQ query

问题

我有一个LINQ语句,如下所示:

var query = from s in persons
            where (string.IsNullOrEmpty(name) || s.Name.Trim().Contains(name)) &&
                  (string.IsNullOrEmpty(email) || s.Email.Contains(email)) &&
                  (string.IsNullOrEmpty(zip) || s.Zip == zip)
            select s;

name字段来自用户在网页上输入的名称,然后我需要在persons表中搜索该特定名称。不幸的是,数据库中的名字名和姓都在同一列中,而另一个问题是名字名和姓之间有两个空格,例如,如果名字是Steve Ramsey。数据库中的名字是这样的:

Steve  Ramsey

并不是所有的名字都是这样存储的,只有少数名字是这样的。我有正则表达式来消除一个额外的空格:

Regex regex = new Regex("[ ]{2,}", options);
CustName = regex.Replace(CustName, " ");

我不确定如何将这个正则表达式放入LINQ查询中。

英文:

I have a LINQ statement like this:

var query = from s in persons
            where (string.IsNullOrEmpty(name) || s.Name.trim().contains(name)) &&
                  (string.IsNullOrEmpty(email) || s.Email.contains(email)) &&
                  (string.IsNullOrEmpty(zip) || s.Zip == zip)
            select s;

The name field is coming from the user who can type the name on the web page and then I need to search the persons table for that particular name. Unfortunately, the name First Name and Last name are in the same column in the database and the other issue is there are two spaces between first Name and Last Name so for e.g. if the name is Steve Ramsey. the name in the database is this way:

Steve  Ramsey

Not all the names are stored this way, only few names are like this. I have the Regex to eliminate one extra space:

Regex regex = new Regex("[ ]{2,}", options);
CustName = regex.Replace(CustName, " ");

I am not sure how to put this regex in LINQ query

答案1

得分: 0

直接在LINQ-to-SQL中使用Regex.Replace是不可能的。我有两种选择,我认为第一种是最好的。使用SqlMethods.Like方法来实现你想要的功能。

我的解决方案:

var query = from s in persons
            where (string.IsNullOrEmpty(name) || SqlMethods.Like(s.Name, "%" + name + "%")) &&
                  (string.IsNullOrEmpty(email) || s.Email.Contains(email)) &&
                  (string.IsNullOrEmpty(zip) || s.Zip == zip)
            select s;

这应该解决你的问题。不要忘记导入这个类:

using System.Data.Linq.SqlClient;
英文:

Directly using Regex.Replace in LINQ-to-SQL is not possible. There are two options in my mind and I think the first one is the best one. Use SqlMethods.Like method to do what you wanted to do.

My Solution:

var query = from s in persons
            where (string.IsNullOrEmpty(name) || SqlMethods.Like(s.Name, "%" + name + "%")) &&
                  (string.IsNullOrEmpty(email) || s.Email.Contains(email)) &&
                  (string.IsNullOrEmpty(zip) || s.Zip == zip)
            select s;

This should fix your problem. Don't forget to import this class:

using System.Data.Linq.SqlClient;

huangapple
  • 本文由 发表于 2023年6月8日 06:58:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定