Home > Mobile >  How to filter data from SQL concatenating two columns in c#?
How to filter data from SQL concatenating two columns in c#?

Time:09-20

Is there a way to do .Where(c. => c.filters.Name) but also check for surname?

SO: Given this input filter "John Doe" where John is the name and Doe is the surname. And given that i have two column in the database one for name and one for surname how can i filter correclty:

For example:

  • if user inputs "John" i'll filter for all the John in the database (including John Doe)
  • AND if user inputs "Doe" i'll filter for all the Doe in the database (including John Doe)
  • if user inputs "John Doe" i'll filter for all the John Doe in the database (can't get this one to work)

I tried this:

query.Where(x => x.Name.Contains(filters.Name.Trim()) || x.Surname == filters.Name.Trim());

But that does not filter when the input is "John Doe"... any idea on how to do this?

CodePudding user response:

Add the property FullName your model.

[NotMapped]
public string FullName => $"{Name} {LastName}"

Then you can search using

string pattern = $@"(\w*{search.ToLower().Trim()}\w*)";
query.Where(x => Regex.IsMatch(x.FullName.ToLower(), pattern));

You will need to add

using System.Text.RegularExpressions

CodePudding user response:

should be as simple as

query.Where(x => (x.Name   " "   x.Surname).ToLower().Contains(filters.Name.Trim()));
  • Related