【问题标题】:Case insensitive search function in C#C#中不区分大小写的搜索功能
【发布时间】:2016-07-06 04:24:19
【问题描述】:

我想在我的DataGridView 上创建一个搜索功能,在按钮点击事件之后。为此,我使用了以下源代码:

chargerDataGrid();
dg_logiciel.ClearSelection();

string search = txtbox_recherche.Text;
foreach (DataGridViewRow dgvr in dg_logiciel.Rows)
{
    if (!dgvr.Cells[1].Value.ToString().Contains(search))
    {
        dgvr.Visible = false;
    }
}

它正在工作,但我想比较我的两个字符串忽略大小写。为此,我尝试了以下代码:

chargerDataGrid();
dg_logiciel.ClearSelection();

string search = txtbox_recherche.Text;
foreach (DataGridViewRow row in dg_logiciel.Rows)
{
    Regex pattern = new Regex(row.Cells[1].Value.ToString(), RegexOptions.IgnoreCase);
    if (!pattern.IsMatch(search))
    {
        row.Visible = false;
    }
}

这根本不起作用。我是不是在使用 Regex 类或其他什么东西不好?

【问题讨论】:

    标签: c# regex search datagridview


    【解决方案1】:

    不幸的是,.NET 缺少 string.Contains(string, StringComparison) 函数重载。

    但是您可以轻松地将这样的扩展功能添加到您的项目中,因为我们有一个合适的IndexOf重载:

    public static class StringExtensions
    {
        public static bool Contains(this string str, string value, StringComparison comparison)
        {
            return str.IndexOf(value, comparison) >= 0;
        }
    }
    

    然后简单地使用:

    if (!dgvr.Cells[1].Value.ToString().Contains(search, StringComparison.OrdinalIgnoreCase))
    

    或根据您的需要使用CurrentCultureIgnoreCase


    至于您的正则表达式尝试,显然没有必要为此付出如此多的努力,但您的尝试失败是由于以下原因的组合:

    • 您反转了您搜索的值和您搜索的字符串。您必须使用search 字符串作为模式来构建您的正则表达式实例。
    • 说起来,您应该已经转义了搜索值。如果它包含任何正则表达式元字符,则该模式将无效。您本可以为此使用 Regex.Escape

    因此,以下会起作用,但不是完成这项工作的正确方法:

    if (!Regex.IsMatch(row.Cells[1].Value.ToString(), Regex.Escape(search), RegexOptions.IgnoreCase))
    

    【讨论】:

    • 感谢您的帮助和解释!效果很好。
    【解决方案2】:

    在您的回答中,以下参数的含义是什么?它将如何工作?

    this string str
    

    我的意思是this和静态如何共存

    【讨论】:

    • 只需阅读扩展方法。这篇文章应该是一个评论来回答。尽快删除。
    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    相关资源
    最近更新 更多