简体   繁体   中英

Entity Framework convert string value to datetime

I have a table storing a list of dates & time (dd/MM/yyyy) in string format.

What I am trying to do is order the data by DateTime descending, the code below worked just fine but it just orders it by date (dd), So I have to convert it to Datetime to do the right job.

casesBindingSource.DataSource = db.casesSet
                                  .Where(x => x.casestatus == "شفيت")
                                  .OrderByDescending(c => c.dateofrecovery)
                                  .ToList();

try:

casesBindingSource.DataSource = db.casesSet
                                  .Where(x => x.casestatus == "شفيت")
                                  .OrderByDescending(c => DateTime.ParseExact(c.dateofrecovery, "dd/MM/yyyy", Nothing))
                                  .ToList();

Try this approach: .OrderByDescending(c => DateTime.ParseExact(c.dateofrecovery, "dd/MM/yyyy", CultureInfo.InvariantCulture))

Did you try first calling tolist and then running orderby. I know it is a bit inefficient, however it is worth giving a try.

casesBindingSource.DataSource = db.casesSet
                                  .Where(x => x.casestatus == "شفيت")
                                  .ToList()
                                  .OrderByDescending(c => DateTime.ParseExact(c.dateofrecovery, "dd/MM/yyyy",CultureInfo.InvariantCulture).Year)
                                  .ThenByDescending(c => DateTime.ParseExact(c.dateofrecovery, "dd/MM/yyyy", CultureInfo.InvariantCulture).Month)
                                  .ThenByDescending(c => DateTime.ParseExact(c.dateofrecovery, "dd/MM/yyyy", CultureInfo.InvariantCulture).Day);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM