Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatable filtering: linq vs filter?

filtering an memory object ( datatble) :

Is there huge different between doing :

    var t = dt.Select("id=2");

vs

    var g = dt.AsEnumerable().Where(f => f["id"].ToString() == "2");
like image 754
Royi Namir Avatar asked Jan 07 '13 08:01

Royi Namir


2 Answers

I assume that DataTable.Select needs even more memory than Enumerable.Where since the latter is just a loop on the DataRowCollection of the DataTable whereas the old DataTable.Select creates new objects like Select or DataExpression and it even returns new objects(DataRow[]) from the query. Enumerable.Where just uses a predicate in a loop to determine what to return. It's also executed lazily, so you could just take, say 10 rows from the result.

var rows = dt.AsEnumerable()
             .Where(row => row.Field<int>("id") == 2)
             .Take(10); // not possible with DataTable.Select

Both are in-memory queries, so there's not a great difference.

I would chose what is more readable, powerful and maintanable and also strongly typed(Field extensions): Linq-To-DataTable.

like image 169
Tim Schmelter Avatar answered Sep 29 '22 09:09

Tim Schmelter


I suggest you to go through ASP.net forum thread - DataTable.Select Vs DataTable.AsEnumerable().FirstOrDefault

From: Which one to use; Datatable.Select() or LINQ?

LINQ is generally easier to read, on my opinion, than pretty much any other form of data filtering and has the advantage over using DataTable.Select of being, at least partially, strongly-typed making it harder to make mistakes.

LINQ is faster than SELECT for large number of rows, when rows keep increasing, you should see considerable difference.

like image 20
Niranjan Singh Avatar answered Sep 29 '22 09:09

Niranjan Singh