-3

I have a dataset ds and i need to sort the datatabel of the same ds based on a column and the column name is Date. The values on this column is in 'dd MMM yyyy' format.

Anu Basheer A
  • 21
  • 1
  • 4

2 Answers2

0

If you can't change the column type to Date then try Linq solution as below

var recs = dataset.Tables[0].AsEnumerable()
    .OrderBy(x =>DateTime.ParseExact(
             x.Field<string>("Date"),
                           "dd MMM yyyy", 
                           CultureInfo.InvariantCulture));
Damith
  • 62,401
  • 13
  • 102
  • 153
  • You have a typo in there should be dd MM yyyy and DateTime.ParseExact() :) good answer – Dr Schizo Jul 26 '13 at 07:03
  • @Onam sorry, i did't get you – Damith Jul 26 '13 at 07:07
  • Look at the format of the date you are converting it to dd MMM yyyy. Note the 3 characters to represent a month. Also DateTime.ParaseExact is misspelled and just noticed CultureInfo.InvariantCultur needs to be CultureInfo.InvariantCulture (note the 'e' at the end). Other than that perfect :) – Dr Schizo Jul 26 '13 at 07:10
  • @Onam - OP has `MMM`, not `MM`. @Damith - You wrote `ParaseExact` instead of `ParseExact`. – Corak Jul 26 '13 at 07:10
  • @Onam and Corak, Thanks both of you. – Damith Jul 26 '13 at 07:15
-1

That's going to be a problem particularly if it's a large table. The best answer of course, would be to redefine the column as a date type. That way it'll sort and join efficiently. If the table is not large, though, you can reformat the date string to ISO format (YYYY-MM-DD), and it will sort correctly. You didn't mention which database you using, and the string and date functions vary among platforms: here's a SQL Server example:

 SELECT CAST([Date] AS Date) AS real_date,
        my_other_fields
   FROM MyTable

I'm at home, so I don't have a SQL Server to test this on right now (I can update the example in the morning if it doesn't work), but that date format is pretty unambiguous to parse, so I expect that the cast will work okay.

If you want to take care of this entirely on the application side, it should be fairly straightforward to write a string function will reorder the year, month and day in the date string.

Curt
  • 5,518
  • 1
  • 21
  • 35