user2977985
user2977985

Reputation:

take top 10 or 20 rows from dynamic datatable

I have 100 records in my Datable says to be in

DataTable dt=new DataTable();

dt have 100 of records say column name as sub_id(contain int datatype) and subheadername(contain nvarchar(150)) , I want top 20 records from this dt in ascending order

I am putting code as

//dtlcategories.DataSource = dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataBind();

Here dtlcategories is Datalist but on running error is coming as 'System.Data.DataRow' does not contain a property with the name 'subheadername'.

ANSWER IS SOLVED

dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).copytodatatable();
dtlcategories.DataBind();

Upvotes: 8

Views: 27025

Answers (5)

SHM
SHM

Reputation: 1952

this code orders data according to date and takes first 100 row.

 var table = new DataTable();
 var t = table.AsEnumerable();
 var result = t.OrderByDescending(f => f.Field<DateTime>(new DataColumn("Date"))).Take(100);

Update:

var table = new DataTable();
var t = table.AsEnumerable();
var result = t.OrderBy(f => f.Field<String>(new DataColumn("subheadername"))).Take(20)

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66449

There's a couple different ways you can do this using LINQ. These will both return the same results.

dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20);

dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20);

If you're going to use the result as the source of data for another control, you may need to call .ToList() after .Take(x).

Edit:

I changed the column name based on your edit. If you want to sort by id instead (you didn't specify), just replace "subheadername" with "sub_id".

Upvotes: 11

Arindam
Arindam

Reputation: 330

dt.AsEnumerable().OrderBy(row => row["sub_id"]).Take(20);

This will return you IEnumerable. Now iterate through the IEnumerable and add them to another data table. Now your final data table is ready!!

Upvotes: 1

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

A possible solution:

DataRow[] rows = dt.Select("sub_id< 100 ");

Upvotes: 0

Ondrej Janacek
Ondrej Janacek

Reputation: 12616

This query fetches top 20 records from db and then orders them by the sub_id column.

var topTwenty = dt.AsEnumerable().Take(20).OrderBy(r => r.Field<int>("sub_id"));

Upvotes: 2

Related Questions