I want to 开发者_C百科sort a DataTable based on a column which has date value. I was running in to issues so i created following test method:
private static void Test()
{
DateTime testDate = DateTime.Parse("01/01/2011");
DataTable table = new DataTable();
table.Columns.Add("dateValue");
table.Columns.Add("slNo");
DataRow row1 = table.NewRow();
row1["dateValue"] = "01/01/2011";
row1["slNo"] = "1";
DataRow row2 = table.NewRow();
row2["dateValue"] = "01/02/2011";
row2["slNo"] = "1";
DataRow row3 = table.NewRow();
row3["dateValue"] = "02/01/2011";
row3["slNo"] = "1";
DataRow row4 = table.NewRow();
row4["dateValue"] = "01/03/2011";
row4["slNo"] = "1";
table.Rows.Add(row1);
table.Rows.Add(row2);
table.Rows.Add(row3);
table.Rows.Add(row4);
var t = table.AsEnumerable().OrderBy(x => x.Field<DateTime?>("dateValue")).ToList();
}
I get Following error:
Specified cast is not valid.
The date provided can be parsed to DateTime object. But still it get the above error. Any idea what is missing?
I use C# 3.5
Try changing the following line:
table.Columns.Add("dateValue");
to this:
table.Columns.Add("dateValue", typeof(DateTime?));
If you remove the ToList() in last line it works.
var t = table.AsEnumerable().OrderBy(x => x.Field("dateValue")).ToList();
It appears the cast problem happens in the call ToList();
You didn't specify the column type, so try to use object in the Field:
var t = table.AsEnumerable().OrderBy(x => x.Field<DateTime?>("object")).ToList();
精彩评论