Regex in LINQ query

Anjali Agarwal 1,531 Reputation points
2023-06-14T03:34:50.11+00:00

I have a LINQ query 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 s 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 and sometimes three 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

or if the name is Steve Ramsey last

It can be stored in the database like this:

Steve   Ramsey Last

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

Regex regex = new Regex("[ ]{2,}", options);
CustName = regex.Replace(CustName, " ");
or
myString = Regex.Replace(myString, @"\s+", " ");

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

Any help will be greatly appreciated.

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-06-14T06:53:22.8566667+00:00

    Hi @Anjali Agarwal

    how to put this regex in LINQ query.

    To put the regex in the LINQ query, you need to convert the persons as Enumerable or List, using the AsEnumerable, AsAsyncEnumerable, ToList, or ToListAsync methods.

    Refer to the following sample:

                var name = "Steve Ramsey"; //one space
                 
                var query = (from s in _dbcontext.Persons.AsEnumerable()
                            where (Regex.Replace(s.Name, @"\s+", " ").Contains(name))
                            select s).ToList();
    

    The result as below:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.