Question

Je trie les dossiers du datewise datatable avec la colonne TradingDate qui est le type de datetime.

TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";

Maintenant, je veux stocker ces enregistrements classés en fichier csv, mais les enregistrements stockés ne sont pas triés par date.

 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));
    }
 }

Alors, comment stocker les enregistrements triés dans le fichier csv?

Était-ce utile?

La solution

Cette ligne de code;

DataRow row = newTable.DefaultView.Table.Rows[i]; 

fait référence DataTable derrière le DataView non triés. Vous devez utiliser un DataRowView au lieu d'un DataRow et l'accès aux lignes triées de la DataView;

DataRowView row = newTable.DefaultView[i]; 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top