Click here to Skip to main content
15,913,115 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want to sort a datatable string column but column having date in (mm/dd/yyyy) format.

What I have tried:

I tried following but the data is not getting sorted in valid order.
C#
dtData = dtData.AsEnumerable().OrderByDescending(r => (Convert.ToDateTime(r.Field<string>(ColumnName)))).CopyToDataTable();
Posted
Updated 13-Nov-17 3:36am
v5

1 solution

use DateTime.ParseExact Method [^]
dt = dt.AsEnumerable().OrderByDescending(r => (DateTime.ParseExact(r["DateColumnName"] + "", "mm/dd/yyyy", CultureInfo.InvariantCulture))).CopyToDataTable();


if you are worried about null or other string data then DateTime.TryParseExact Method [^] would be the best choice
DataTable dt = new DataTable();
            dt.Columns.Add("DateColumnName");
            dt.Rows.Add("11/14/2017");
            dt.Rows.Add("11/13/2017");
            dt.Rows.Add("11/16/2017");

           

            dt.Columns.Add("NewColumnTemp");
            dt.AsEnumerable().ToList().ForEach(row =>
            {
                string date = row["DateColumnName"] + "";
                DateTime dateTemp;
                DateTime? dateTempNull = null;
                bool isValid = DateTime.TryParseExact(date, "mm/dd/yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTemp);
                row["NewColumnTemp"] = isValid ? dateTemp : dateTempNull;

            });
            DataView dv = dt.DefaultView;
            dv.Sort = "NewColumnTemp desc";
            dt = dv.ToTable();
            dt.Columns.Remove("NewColumnTemp");
 
Share this answer
 
v4
Comments
IamWsk 13-Nov-17 9:38am    
Thank you @Karthik Banglore. Would it handle the null values?Column has some null or blank values too.
Karthik_Mahalingam 13-Nov-17 9:39am    
have updated the solution
IamWsk 13-Nov-17 9:41am    
OK, Let me apply the solution.
IamWsk 13-Nov-17 10:38am    
Now it is sorting like this
NewColumnTemp
31-01-2015
31-01-2014
30-01-2015
Karthik_Mahalingam 13-Nov-17 10:45am    
mm/dd/yyyy

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900