searching by special character on linq

1.5k views Asked by At

I need a searching process on linq like this. For example, I will make searching on Name column,and user enters "Ca?an" word to textbox. Question mark will e used for sprecial search character for this sitution. It will search by Name column and, find Canan,Calan,Cazan etc. I hope I can explain my problem correctly. Can anyone give me an idea about this linq query. Thank in advance...

2

There are 2 answers

0
Oscar Bralo On

You can use this regular expression (if you are using C#) to check for the "Ca?an".

string d = "DDDDDDDDDDCasanDDDDDDDDDD";
Regex r = new Regex(@"Ca([a-zA-Z]{1})an");
string t = r.Match(d).Value;

Output will be:

"Casan"

You have all your colum stored in a database, then do something like:

List<Person> list = new List<Person>(); //Filled
var res = list.Select(x => r.Match(x.Name));

Output will be a IEnumerable with all the "Persons" who contains in the Name "Ca?an", being ? no matter which letter

0
Johan Tegman On

You need to convert your search-syntax into an existing search-engine - I'd suggest Regex. So the steps will be:

  1. Safely convert the entered search-string into Regex-pattern
  2. Perform the search in Linq on name-property

Solution:

1: Safely convert search string by replacing '?' with Regex-version of wildchar:

var userInput = "Ca?an";
var regexPattern = Regex.Escape(userInput).Replace(@"\?", ".");

2: Perform search in Linq (assuming itemList implements IEnumerable):

var results = itemList.Where(item => Regex.IsMatch(item.Name, regexPattern));

Hope this helps!