Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use OrderBy in linq for DataTable in asp.net

Tags:

c#

asp.net

linq

I have two Data table Folder_table and folder_filter. Both the table has two columns FolderName and FolderDateTime . In the Folder_Table i have values like below

FolderName   FolderDateTime

Test1        29/3/2014
Test2        20/12/2014
Test3        4/2/2014
test5        9/6/2014

I am using the below coding to copy 2 rows from Folder_table to folder_filter

folder_filter = Folder_table.Rows.Cast<System.Data.DataRow>().Take(2).CopyToDataTable();

I want to order by descending in FolderDateTime column. how to do that. PLease help

like image 279
user3734234 Avatar asked Jul 14 '14 12:07

user3734234


People also ask

How to Sort DataTable using LINQ?

Now to short the datable I have used a LINQ feature to convert database as IEnumerable and then I have used 'OrderBy' operator to sort IEnumerable with First Name row. It will return a sorted EnumerableRowCollection of rows. Then I have converted EnumerableRowCollection to dataview and then cast as datable. That's it.

How do you sort and filter data using DataView?

The DataView provides several ways of sorting and filtering data in a DataTable: You can use the Sort property to specify single or multiple column sort orders and include ASC (ascending) and DESC (descending) parameters.

How do you use order by in lambda expression?

OrderBy( ) and OrderByDescending( ) For basic data types (e.g., string, int, decimal, etc.), Lambda expressions make sorting easy: using System. Linq; List<Employee> sortedList = employees. OrderBy(e => e.


1 Answers

If your field data type is DateTime then you can use:

var sortedTable = Folder_table.AsEnumerable()
                 .OrderBy(r => r.Field<DateTime>("FolderDateTime"))
                 .CopyToDataTable();

If your column type is string then first you have to parse these values to DateTime type object. Use DateTime.ParseExact with format d\M\yyyy like:

var sortedTable = Folder_table.AsEnumerable()
                 .OrderBy(r => DateTime.ParseExact(r.Field<string>("FolderDateTime"),
                                                    "d/M/yyyy", CultureInfo.InvariantCulture))
                 .CopyToDataTable();

You should see: LINQ to DataSet/ DataTable - MSDN

like image 191
Habib Avatar answered Oct 17 '22 09:10

Habib