C# 在数据表中查找值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/633819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:08:14  来源:igfitidea点击:

Find a value in DataTable

c#datatable

提问by Dhana

Is there a way to find a value in DataTable in C# without doing row-by-row operation?

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

The value can be a part of (a substring of row[columnName].value , separated by comma) a cell in the datatable and the value may be present in any one of columns in the row.

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

采纳答案by Andy Rose

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

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

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

查看您的要求,您的过滤器表达式必须具有一定的通用性才能使这项工作正常进行。

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

回答by Canavar

Maybe you can filter rows by possible columns like this :

也许您可以按如下可能的列过滤行:

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

回答by Marc Gravell

AFAIK, there is nothing built in for searching all columns. You can use Findonly against the primary key. Selectneeds specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

AFAIK,没有内置任何内容来搜索所有列。您Find只能对主键使用。Select需要指定的列。您也许可以使用 LINQ,但最终这只是执行相同的循环。也许只是自己展开它?至少它会是可读的。

回答by user4723665

this question asked in 2009 but i want to share my codes:

这个问题是在 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