Sort a string column by datetime in a DataTable

前端 未结 4 802
名媛妹妹
名媛妹妹 2021-01-15 14:45

I am trying to sort a DataTable on a string column by DateTime.

For various reasons, the column must be left as a string

相关标签:
4条回答
  • 2021-01-15 14:47

    Try Add while create DataTable

        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;
    
    0 讨论(0)
  • 2021-01-15 14:49

    Stumbled upon a method right after I posted.

    EnumerableRowCollection<DataRow> query = from row in dataTable.AsEnumerable()
                                             orderby DateTime.Parse(row.Field<string>(propertyName)) ascending
                                             select row;
    dataTable = query.AsDataView().ToTable();
    
    0 讨论(0)
  • 2021-01-15 14:54
            List<DataRow> rows = new List<DataRow>();
            foreach (DataRow row in table.Rows)
            {
                rows.Add(row);
            }
            rows.Sort((r1,r2)=>DateTime.Parse((string)r1["columnname"]).CompareTo(DateTime.Parse((string)r2["columnname"])));
            var clone = table.Clone();
            rows.ForEach(r => clone.Rows.Add(r.ItemArray));
            return clone;
    
    0 讨论(0)
  • 2021-01-15 15:12

    You can sort dates as a string if you use the format YYYYMMDD

    0 讨论(0)
提交回复
热议问题