I am trying to sort a DataTable
on a string
column by DateTime
.
For various reasons, the column must be left as a string
Try Add while create DataTable
table.Columns.Add("dateValue", typeof(DateTime?));
var orderedRows = from row in dt.AsEnumerable()
orderby row.Field<DateTime>("Date")
select row;
DataTable tblOrdered = orderedRows.CopyToDataTable();
(Or)
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.Parse(row.Field<string>("Date"), CultureInfo.InvariantCulture)
orderby date
select row;
Stumbled upon a method right after I posted.
EnumerableRowCollection<DataRow> query = from row in dataTable.AsEnumerable()
orderby DateTime.Parse(row.Field<string>(propertyName)) ascending
select row;
dataTable = query.AsDataView().ToTable();
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
rows.Sort((r1,r2)=>DateTime.Parse((string)r1["columnname"]).CompareTo(DateTime.Parse((string)r2["columnname"])));
var clone = table.Clone();
rows.ForEach(r => clone.Rows.Add(r.ItemArray));
return clone;
You can sort dates as a string if you use the format YYYYMMDD