Search code examples
.netlinqdatatable

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

Solution

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