Rob Bowman
Rob Bowman

Reputation: 8711

Linq sort by string that is datetime

I have the following view model:

public class MvcFormsViewModel
{
    public int RecCount { get; set; }
    public List<Dictionary<string, string>> PageOfRecords { get; set; }

    public MvcFormsViewModel()
    {
        PageOfRecords = new List<Dictionary<string, string>>();
    }
}

My controller sorts the data with the following:

vm.PageOfRecords = vm.PageOfRecords.OrderBy(x => x.ContainsKey(sortValue) ? x[sortValue] :
                                                            string.Empty).Skip(startIndex).Take(endIndex - startIndex).ToList();

The sortValue is passed into the controller from the view - it will be the name of one of the columns - also a key in the dictionary.

My problem is, sometimes the value of "sortValue" param is a timestamp, in which case I would like linq to sort as datetime rather than string. How could I do this?

Upvotes: 0

Views: 2422

Answers (1)

MartinM
MartinM

Reputation: 1806

Something like:

 vm.PageOfRecords = vm.PageOfRecords
    .Skip(startIndex)
    .Take(endIndex - startIndex)
    .OrderBy(x => x.ContainsKey(sortValue) ? DateTime.Parse(x[sortValue]) : DateTime.Min).ToList();

But that may involve a lot of casting if the dataset is large. As someone suggested, if the data type was already DateTime this would make things easier

Upvotes: 1

Related Questions