[SOLVED] How to filter data from SQL concatenating two columns in c#? – Stack Overflow


This Content is from Stack Overflow. Question asked by devludo

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?


Add the property FullName your model.

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

This Question was asked in StackOverflow by devludo and Answered by BugzyGeek It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?