Jonie Shih
Jonie Shih

Reputation: 252

Sort a string column by datetime in a DataTable

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

For various reasons, the column must be left as a string data type. I know I can copy the data out into another table, convert that column to a DateTime column, sort on that and copy it back but I'm wondering if there's a neater way.

I've tried the basics of DefaultView and LINQ to no prevail.

Upvotes: 2

Views: 13769

Answers (4)

Kanjie Lu
Kanjie Lu

Reputation: 1047

        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;

Upvotes: 0

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

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;

Upvotes: 3

TGH
TGH

Reputation: 39248

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

Upvotes: 0

Jonie Shih
Jonie Shih

Reputation: 252

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

Upvotes: 3

Related Questions