Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a string in all DataTable columns

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;
like image 789
meYnot Avatar asked May 20 '26 12:05

meYnot


1 Answers

You can use LINQ. It wouldn't be any faster, because you still need to look at each cell in case the value is not there, but it will fit in a single line:

return dataTable
    .Rows
    .Cast<DataRow>()
    .Any(r => r.ItemArray.Any(c => c.ToString().Contains("whatever")));

For searching for random text and returning an array of rows with at least one cell that has a case-insensitive match, use this:

var text = "whatever";
return dataTable
    .Rows
    .Cast<DataRow>()
    .Where(r => r.ItemArray.Any(
        c => c.ToString().IndexOf(text, StringComparison.OrdinalIgnoreCase) > 0
    )).ToArray();
like image 142
Sergey Kalinichenko Avatar answered May 22 '26 01:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!