I am working on same datatable related operation on data, what would be the most efficient way to use linq on datatable-
var list = dataSet.Tables[0]
.AsEnumerable()
.Where(p => p.Field<String>("EmployeeName") == "Jams");
OR
var listobj = (EnumerableRowCollection<DataRow>) dataSet.Tables[0].Rows
.Cast<DataRow>()
.Where(dr => dr["EmployeeName"].ToString() == "Jams");
.AsEnumerable()
internally uses .Rows.Cast<DataRow>()
, at least in the reference implementation. It does a few other bits as well but nothing that would appreciably affect performance.
.AsEnumerable()
and .Field
do a lot of extra work that is not needed in most cases.
Also, field lookup by index is faster than lookup by name:
int columnIndex = dataTable.Columns["EmployeeName"].Ordinal;
var list = dataTable.Rows.Cast<DataRow>().Where(dr => "Jams".Equals(dr[columnIndex]));
For multiple names, the lookup is faster if the results are cached in a Dictionary
or Lookup
:
int colIndex = dataTable.Columns["EmployeeName"].Ordinal;
var lookup = dataTable.Rows.Cast<DataRow>().ToLookup(dr => dr[colIndex]?.ToString());
// .. and later when the result is needed:
var list = lookup["Jams"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With