在所有DataTable列中查找一个字符串 [英] Find a string in all DataTable columns

查看:567
本文介绍了在所有DataTable列中查找一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个快速的方式来查找所有的数据列中的字符串!
跟随没有工作,因为我想在所有列值中搜索。

I am trying to find a fast way to find a string in all datatable columns! Followed is not working as I want to search within all columns value.

string str = "%whatever%";
foreach (DataRow row in dataTable.Rows)
    foreach (DataColumn col in row.ItemArray)
        if (row[col].ToString() == str) return true;


推荐答案

这可以通过过滤来实现。根据所有列创建一个(可重复使用的)过滤字符串:

This can be achieved by filtering. Create a (re-usable) filtering string based on all the columns:

        bool UseContains = false;
        int colCount = MyDataTable.Columns.Count;


        string likeStatement = (UseContains) ? " Like '%{0}%'" : " Like '{0}%'"; 
        for (int i = 0; i < colCount; i++)
        {
            string colName = MyDataTable.Columns[i].ColumnName;
            query.Append(string.Concat("Convert(", colName, ", 'System.String')", likeStatement));


            if (i != colCount - 1)
                query.Append(" OR ");
        }

        filterString = query.ToString();

现在,您可以获得其中一列与您的搜索字符串匹配的行:

Now you can get the rows where one of the columns matches your searchstring:

 string currFilter = string.Format(filterString, searchText);
 DataRow[] tmpRows = MyDataTable.Select(currFilter, somethingToOrderBy);

这篇关于在所有DataTable列中查找一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆