'DateTime.ToShortDateString() orderby with linq
Suppose there are two products in the db.
I want to sort them by date.
The date is saved as a string in the database.
System.FormatException: 'String '3/23/2022' was not recognized as a valid DateTime.'
{
Name: "Product1",
Date: "23-03-2022",
}
{
Name: "Product2",
Date: "24-03-2022",
}
var orderedList = db.Product.OrderByDescending(x => DateTime.Parse(x.Date,
CultureInfo.CreateSpecificCulture("en-GB"))).ToList();
Solution 1:[1]
var orderedList = db.Product.Select(item => new {
item,
ymd = String.Concat(item.Date.Substring(6, 4) ,'-', item.Date.Substring(3, 2), '-', item.Date.Substring(0, 2)) /* yyyy-MM-dd format */
}).Select(x => new {
x.item,
datediffvalue = SqlFunctions.DateDiff("DD", "1899-12-30", x.ymd)
}).OrderByDescending(x => x.datediffvalue ?? 0).Select(x => x.item);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
