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);
}
尝试像这样声明你的正则表达式
Regex regEx = new Regex(text, RegexOptions.IgnoreCase);
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);
}
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.
链接地址: http://www.djcxy.com/p/21032.html上一篇: C#如果等于大小写不敏感