Nitin Arote
Nitin Arote

Reputation: 71

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

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");

Upvotes: 6

Views: 9644

Answers (4)

Slai
Slai

Reputation: 22876

.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"];

Upvotes: 1

Jussi Kosunen
Jussi Kosunen

Reputation: 8307

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

Upvotes: 1

Ric
Ric

Reputation: 13248

Interestingly enough, AsEnumerable() returns EnumerableRowCollection<DataRow> which if you look into the code for this, you will see the following:

this._enumerableRows = Enumerable.Cast<TRow>((IEnumerable) table.Rows);

So I would say that they are basically equivalent!

Upvotes: 1

Anton Gogolev
Anton Gogolev

Reputation: 115741

Define "efficient".

From performance standpoint, I doubt that there are any significant differences between these two options: the overall run-time will be dominated by the time required to do network I/O, not the time required to do casting.

From pure code style point of view, second one looks too unelegant to me. If you can get away with all-LINQ solution, go with it as it's generally (IMO, at least) more readable by virtue of being declarative.

Upvotes: 0

Related Questions