Glory Raj
Glory Raj

Reputation: 17701

Case insensitive LIKE condition in LINQ (with Regular Expression)

I have following code that works if the search text and the items in the list are of same case (lower case / upper case). If there is a mixed casing it is not working,. How can we make it case insensitive search.

var text = "c";
var myStrings = new List<string>() { "Aa", "ACB", "cc" };
var regEx = new System.Text.RegularExpressions.Regex(text);
var results = myStrings
        .Where<string>(item => regEx.IsMatch(item))
        .ToList<string>();

EDIT :

I need to pass that string with Case Insensitive to the method how can i do that ...

  public ActionResult GetItems(string text)
  {
        ContextObject contextObject = new ContextObject();          
        TransactionHistory transactionhistory = new TransactionHistory();
        System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(text, RegexOptions.IgnoreCase);
        var items = transactionhistory.GetItems(contextObject, text);

        return Json(items, JsonRequestBehavior.AllowGet);                     
  }

Upvotes: 2

Views: 617

Answers (3)

Ehsan
Ehsan

Reputation: 32681

you need to use the overload which takes RegexOptions.IgnoreCase

Example

 RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
 System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(text, options);

EDIT:

RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;            
var text = "c";
var myStrings = new List<string>() { "Aa", "ACB", "cc" };
var regEx = new System.Text.RegularExpressions.Regex(text, options);
var results = myStrings
             .Where<string>(item => regEx.IsMatch(item))
             .ToList<string>();

//you will have 2 items in results
foreach(string s in results)
{
    GetItems(s);
}

Upvotes: 1

Gonzix
Gonzix

Reputation: 1206

Based in your code, why using a regex? I would use a regex only with complex text patterns. In this case is way easier to use string.IndexOf() like in

var text = "c";
var myStrings = new List<string>() { "Aa", "ACB", "cc" };
var results = myStrings
    .Where(item => item.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0)
    .ToList();

I have al removed the explicit use of string in where and toList as it is applied by default.

Upvotes: 0

TGH
TGH

Reputation: 39258

Try to declare your regex like this

Regex regEx = new Regex(text, RegexOptions.IgnoreCase);

Upvotes: 5

Related Questions