I have a DataTable with some n number of columns and array of string to search in this table. I want to search all these strings in DataTable and store matching strings in list.
Columns in DataTable are dynamic so using below code I got list of Columns from DataTable.
But not sure how to search and get matching records using LINQ or any other technique with best feasible approach.
DataColumn[] cols = dt.Columns.Cast<DataColumn>().ToArray();
This should work:
DataColumn[] cols = dt.Columns.Cast<DataColumn>().ToArray();
var rows = dt.AsEnumerable();
List<string> foundList = searchList
.Where(s => rows.Any(r => cols.Any(c => r[c].ToString().Equals(s))))
.ToList();
But this would be more efficient:
HashSet<string> searchStrings = new HashSet<string>(searchList); // or use a HashSet<string> instead of a list in the first place
List<string> foundList = new List<string>();
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> matches = cols
.Select(c => row[c].ToString())
.Where(searchStrings.Contains); // Contains is O(1) operation
foreach (string match in matches)
{
foundList.Add(match);
searchStrings.Remove(match); // Remove is O(1) operation. It has another advantage: at the end searchStrings contains only strings that were not found
}
}