Reputation: 14507
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.
Upvotes: 32
Views: 181708
Reputation: 15
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
Upvotes: -5
Reputation: 1064004
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.
Upvotes: 8
Reputation: 48098
Maybe you can filter rows by possible columns like this :
DataRow[] filteredRows =
datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
Upvotes: 17
Reputation: 17014
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 + "%'");
Upvotes: 60