Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between datatable.Rows.Cast<DataRow> and datatable.AsEnumerable() in Linq C#

Tags:

c#

linq

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");
like image 730
Nitin Arote Avatar asked Oct 30 '22 20:10

Nitin Arote


2 Answers

.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.

like image 109
Jussi Kosunen Avatar answered Nov 13 '22 15:11

Jussi Kosunen


.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"];
like image 28
Slai Avatar answered Nov 13 '22 17:11

Slai