LINQ中的不区分大小写的LIKE条件(带正则表达式)

时间:2013-08-29 05:50:40

标签: c# linq

如果搜索文本和列表中的项目具有相同的大小写(小写/大写),我可以使用以下代码。如果有混合外壳则无法正常工作。我们怎样才能使它不区分大小写搜索。

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>();

编辑:

我需要将带有Case Insensitive的字符串传递给方法,我该怎么做...

  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);                     
  }

3 个答案:

答案 0 :(得分:5)

尝试声明你的正则表达式

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

答案 1 :(得分:1)

你需要使用RegexOptions.IgnoreCase

的重载

实施例

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

编辑:

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);
}

答案 2 :(得分:0)

根据您的代码,为什么要使用正则表达式?我只使用复杂文本模式的正则表达式。在这种情况下更容易使用string.IndexOf(),如

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

我已经删除了在默认情况下应用的where和toList中字符串的显式使用。

相关问题