I need to match element of the JSON array element in c# for filter autocomplete in c#. Here is my code:
string firstname = "h";
List<user> userlist = new List<user>();
user user1 = new user();
user1.firstname = "Hardik";
user1.lastname = "Gondalia";
user user2 = new user();
user2.firstname = "John";
user2.lastname = "Abraham";
user user3 = new user();
user3.firstname = "Will";
user3.lastname = "Smith";
user user4 = new user();
user4.firstname = "Martin";
user4.lastname = "Luthor";
var myRegex = new Regex(".*\\b" + firstname + "\\b.*");
var u = userlist.Where(i => myRegex.IsMatch(i.firstname)).ToList();
return Json(u, JsonRequestBehavior.AllowGet);
I am posting an answer since there are several issues here.
First, these first names do not contain
h as a whole word and you defined
\b in your pattern to match firstname as a whole word. Check word boundary topic.
Hardik contains an uppercase
H (so, you should consider passing RegexOptions.IgnoreCase flag to myRegex).
Regex.IsMatch also finds partial matches, you do not need
.* in your pattern at all.
Judging by the code, you may achieve that without a regex, use
userlist.Where(i => culture.CompareInfo.IndexOf(i.firstname, firstname, CompareOptions.IgnoreCase) >= 0).ToList()