How to store sorted records in csv file ?
- by Harikrishna
I sort the records of the datatable datewise with the column TradingDate which is type of datetime.
TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";
Now I want to display these sorted records into csv file but it does not display records sorted by date.
TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";TableWithOnlyFixedColumns.Columns["TradingDate"].ColumnName + "] 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 Text Document (3).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));
                }
            }
So how to store sorted records in csv file ?