我使用TradingDate
datetime.
对日期数据表的记录进行排序
TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";
现在我想将这些已排序的记录存储到csv文件中,但存储的记录不按日期排序。
TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";
DataTable newTable = TableWithOnlyFixedColumns.Clone();
newTable.DefaultView.Sort = TableWithOnlyFixedColumns.DefaultView.Sort;
foreach (DataRow oldRow in TableWithOnlyFixedColumns.Rows)
{
newTable.ImportRow(oldRow);
}
// we'll use these to check for rows with nulls
var columns = newTable.DefaultView.Table.Columns.Cast<DataColumn>();
using (var writer = new StreamWriter(@"C:\Documents and Settings\Administrator\Desktop\New.csv"))
{
for (int i = 0; i < newTable.DefaultView.Table.Rows.Count; i++)
{
DataRow row = newTable.DefaultView.Table.Rows[i];
// check for any null cells
if (columns.Any(column => row.IsNull(column)))
continue;
string[] textCells = row.ItemArray
.Select(cell => cell.ToString()) // may need to pick a text qualifier here
.ToArray();
// check for non-null but EMPTY cells
if (textCells.Any(text => string.IsNullOrEmpty(text)))
continue;
writer.WriteLine(string.Join(",", textCells));
}
}
那么如何在csv文件中存储已排序的记录?
答案 0 :(得分:1)
这行代码;
DataRow row = newTable.DefaultView.Table.Rows[i];
引用DataView后面的未排序DataTable。您需要使用DataRowView而不是DataRow,并从DataView访问已排序的行;
DataRowView row = newTable.DefaultView[i];