【问题标题】:Find a pattern in a Generic List在通用列表中查找模式
【发布时间】:2014-02-13 03:38:13
【问题描述】:

我有一个通用列表,我想在列表中搜索与特定模式匹配的项目。

例如,如果我的列表包含:

  • 站立
  • 安妮
  • 表格
  • 斯坦

如果我的模式是“an”,那么无论大小写如何,我都需要在列表中搜索文本中包含“an”的任何项目。在这种情况下,它将返回:stand、Anne 和 Stan。

这是我目前所拥有的(其中 TextBox1 包含模式):

string str = array1.Find(item => item == TextBox1.Text.Trim());

if (str != "")
{
    Label3.Text = "List Item Found";
}
else
{
    Label3.Text = "List Item Not Found.";
}

任何帮助表示赞赏!

谢谢!

【问题讨论】:

    标签: asp.net regex list arraylist generic-list


    【解决方案1】:

    您可能应该使用 LINQ:

    var matches = array1.Where(x => x.Contains(TextBox1.Text.Trim())).ToList();
    

    要使其不区分大小写,请使用IndexOf:

    var matches = array1.Where(x => x.IndexOf(TextBox1.Text.Trim(), StringComparison.OrdinalIgnoreCase) != -1).ToList();
    

    【讨论】:

    • 谢谢!我会看看 - 这种方法是否适用于文本的不同大小写(即大写或小写)?
    • 不,Contains 区分大小写。我已经用不区分大小写的解决方案更新了我的答案。
    • 非常感谢...当我尝试运行时,它的意思是“无法声明局部变量 x”。我错过了什么吗?
    • 好的,具体信息是什么?
    • 不能在此范围内声明名为“x”的局部变量,因为它会给“x”赋予不同的含义,它已在“父或当前”范围中用于表示其他内容
    【解决方案2】:
    var regex = new RegEx("an", RegexOptions.IgnoreCase);
    var anyMatches = array1.Any(x => regex.IsMatch(x));
    if(anyMatches)
    {
        Label3.Text = "List Item Found";
    }
    else
    {
        Label3.Text = "List Item Not Found";
    }
    

    【讨论】:

    • 取决于您可能想要使用已编译正则表达式的大小。
    • 非常感谢@Aron。我会看看这个方法。是否区分大小写?
    • 取决于您的正则表达式。见RegexOptions.IgnoreCase
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2019-11-29
    • 2014-11-18
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多