C#.NET: Get Top and Bottom n Rows from DataTable using LINQ

LINQ, introduced in late 2007 is a way of querying data in arrays, lists, enumerable classes, XML,  relational database s and anything...




LINQ, introduced in late 2007 is a way of querying data in arrays, lists, enumerable classes, XML, relational databases and anything built on these.This post explains how to get the top and bottom n number of  records from C# DataTable without looping through each row using LINQ queries. A LINQ query operation consists of three actions: obtain the data source or sources, create the query, and execute the query.

For this example let me create a datatable with three columns and four rows such as this,

            DataTable dt = new DataTable();
            dt.Columns.Add("Column1");
            dt.Columns.Add("Column2");
            dt.Columns.Add("Column3");
            dt.Rows.Add("A", "B", "C");
            dt.Rows.Add("D", "E", "F");
            dt.Rows.Add("G", "H", "I");
            dt.Rows.Add("J", "K", "L");

To get the top two rows use the following query,

DataTable dt1 = dt.AsEnumerable().Take(2).CopyToDataTable();

This will produce the following output when bound to a gridview,

Column1Column2Column3
ABC
DEF

To get the last two rows use the following query,

DataTable dt1 = dt.AsEnumerable().Reverse().Take(2).CopyToDataTable();

Output:

Column1Column2Column3
JKL
GHI


Subscribe to GET LATEST ARTICLES!


Related

Dot Net 2176976618474508337

Post a comment

  1. Nice post! Educational content developer for K12 can face challenges while developing content, as every bit of information needs to be aligned to the learning objectives and the corresponding standards of the curriculum framework.
    copy editing services

    ReplyDelete

emo-but-icon

SUBSCRIBE


item