user1884709
user1884709

Reputation: 145

Select top N with record from DataTable with some sorting using Linq

I have created a DataTable. I have populated the rows of the DataTable after some operations.

I am very new to Linq I want to Get the Top "N" Records from the DataTable implementing also some paging.

Let dataTable is the DataTable having some data.

I am need something like this

 var Query = from d in dataTable
        Order by columnName
        skip( some records pageSize * pageNumber)
        Select top N from dataTable

The column Name, Page size ,pageNumber and the N will passed as arguments

Upvotes: 0

Views: 6310

Answers (3)

Likurg
Likurg

Reputation: 2760

Try this

var Query = dataTable.Select(o=>o).OrderBy(o=>o.columnName).Skip(pageSize * pageNumber).Take(N);

EDIT

For pass column name you should to add this code

    public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, SortField);
        var exp = Expression.Lambda(prop, param);
        string method = Ascending ? "OrderBy" : "OrderByDescending";
        Type[] types = new Type[] { q.ElementType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }

And then you could call it in this way

var values = dataTable.OrderByField("columnName");

Upvotes: 1

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

Try this,

int numberOfObjectsPerPage = 20;
var queryResultPage = dataTable.OrderBy(c => c.columnName).Select(r => r).Skip(numberOfObjectsPerPage * pageNumber).Take(numberOfObjectsPerPage);

Upvotes: 1

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Try this:

var query = dataTable.AsEnumerable()
        .OrderBy(c => c.columnName)
        .Select(r => new {...})
        .Skip(10)
        .Take(5)

Upvotes: 3

Related Questions