31

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

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.

4 Answers 4

59

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.

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

myDataTable.Select("columnName1 like '%" + value + "%'");
2
  • 1
    how can we do the above syntax with linq.
    – Karan
    May 5, 2011 at 11:12
  • how can you then use this Array as a DataSource for a ComboBox?
    – Mike W
    Oct 16, 2019 at 14:16
17

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
1
  • 5
    if you want exact value: DataRow[] filteredRow = datatable.Select("ColumnName='value'");
    – Nicola
    Apr 9, 2015 at 10:13
8

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs 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.

-5

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

    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
2
  • 2
    This is a C# question, not VB.
    – AzNjoE
    Nov 13, 2015 at 20:41
  • and loops on rows and columns, something that the OP wants to avoid
    – bluish
    Dec 11, 2015 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.