[英]How do I sort DataTable by ascending dates?
My c# code downloads stock quotes into a DataTable object. 我的C#代码将股票报价下载到DataTable对象中。 The data comes as descending dates on the first column.
数据以降序日期显示在第一列上。 I would like to sort this table as ascending dates.
我想将此表按升序排序。 I've tried the following:
我尝试了以下方法:
table.DefaultView.Sort = "Date";
sorts the table as if it were of string type, eg: "1/1/1994", "1/1/1995", "1/1/1996" instead of the desired "1/1/1994", "1/2/1994", "1/3/1994". 对表进行排序,就好像它是字符串类型一样,例如:“ 1/1/1994”,“ 1/1/1995”,“ 1/1/1996”,而不是所需的“ 1/1/1994”,“ 1 / 2/1994”,“ 1/3/1994”。
Now, the following raises InvalidCastException. 现在,以下引发InvalidCastException。
var newTable = table.AsEnumerable().OrderBy(r => r.Field<DateTime>("Date")).CopyToDataTable();
Note: This sorting happens in a method that returns a DataTable object. 注意:这种排序发生在返回DataTable对象的方法中。
[UPDATE] this is how I create and fill the table from a List where each entry is formatted as eg: "1/1/1994,21.01,22,21,21.01,23131,21.01" [更新]这就是我从列表中创建和填充表格的方式,其中每个条目的格式均如下:“ 1/1 / 1994,21.01,22,21,21.01,23131,21.01”
List<string> list = Downloaders.DownloadContentToList(symbol);
DataTable table = new DataTable(symbol);
table.Columns.Add("Date");
table.Columns.Add("Open");
table.Columns.Add("High");
table.Columns.Add("Low");
table.Columns.Add("Close");
table.Columns.Add("Volume");
table.Columns.Add("Adj Close");
for (int i = 0; i < list.Count; i++)
{
string[] cols = list[i].Split(',');
DateTime date = Convert.ToDateTime(cols[0]);
double open = Convert.ToDouble(cols[1]);
double high = Convert.ToDouble(cols[2]);
double low = Convert.ToDouble(cols[3]);
double close = Convert.ToDouble(cols[4]);
double volume = Convert.ToDouble(cols[5]);
double adjClose = Convert.ToDouble(cols[6]);
table.Rows.Add(date, open, high, low, close, volume, adjClose);
}
When you create the datatable you have to specify that it is a date even if it is in string format: 创建数据表时,即使它是字符串格式,也必须指定它是一个日期:
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;
This is a similar question but I think the answer also applies to you. 这是一个类似的问题,但我认为答案也适用于您。
The "Date" column should be added as so: “日期”列应按以下方式添加:
table.Columns.Add("Date", typeof(DateTime));
rather than 而不是
table.Columns.Add("Date");
When Creating Your Table You Should add "date" column as : 创建表时,应将“日期”列添加为:
table.Columns.Add("Date", typeof(DateTime));
then : 然后 :
table.DefaultView.Sort = "Date desc";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.