First of all: if, you would like to use
foreach(...)
loop, i'd move few lines of your code outside the
foreach(...)
loop due to the efficiency. Those are the lines, where you open Excel connection and fill in datatable.
Second of all: you don't need second loop (
foreach (DataRow r in sheets.Rows)
), because you're using
Select
method to filter data!
foreach(string ms in meassteps)
{
DataRow[] msrows= dt.Select(string.Format("measstep Like %{0}%", ms));
}
Another way is to use
Linq.
If you would like to filter datatable by comparing each row to the collection of strings, you're able to achieve that by using
Where()
+
Any()
:
var filteredrows = dt.AsEnumerable()
.Where(x=> meassteps.Any(y=> x.Field<string>("measstep").Contains(y)))
.ToList();
or cross join:
var filteredrows1 = from dr in dt.AsEnumerable()
from ms in meassteps
where dr.Field<string>("measstep").Contains(ms)
select dr;