在DataTable中查找值

时间:2009-03-11 09:12:12

标签: c# datatable

有没有办法在C#中的DataTable中找到一个值而不进行逐行操作?

该值可以是(行[columnName] .value的子字符串,以逗号分隔)数据表中的单元格的一部分,该值可以出现在行的任何一列中。

4 个答案:

答案 0 :(得分:54)

DataTable或DataSet对象将具有Select方法,该方法将根据作为参数传入的查询返回DataRow结果数组。

考虑到你的要求,你的过滤表达必须有点普遍才能使它发挥作用。

myDataTable.Select("columnName1 like '%" + value + "%'");

答案 1 :(得分:14)

也许你可以按照这样的可能列过滤行:

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

答案 2 :(得分:8)

AFAIK,没有内置搜索所有列的内容。您只能对主键使用FindSelect需要指定的列。你也许可以使用LINQ,但最终这只是做同样的循环。也许只是自己展开?它至少可以读取。

答案 3 :(得分:-1)

这个问题在2009年提出,但我想分享我的代码:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function