I have this query that fetches me some items that have a registered request, I created a class to store the item and request data in strings, and I need to sort them by the date of creation from the latest to the oldest.
var Items = await this.ItemsRepository.GetAllAsync(expression);
var report = new List<RegisteredOrders>();
foreach (var item in Items)
{
var request = await this.RequestRepository.GetOneAsync(x => !x.Deleted && x.Id == item.requestId);
report.Add (new RegisteredRequest
(
requestDate: request.CreatedAt.ToString("dd/MM/yyyy"),
requestNum: request.RequestCode,
itemDate: item.CreatedAt.ToString("dd/MM/yyyy"),
itemNum: item.ItemCode
));
}
var orderReport = report.OrderBy(x => x.requestDate).ThenBy(x => x.itemDate);
return orderReport.ToList();
tried to use OrderBy but it's not working, What's happening?
CodePudding user response:
Do you have control over the RegisteredRequest Class? My approach would be to keep the property you assign to as DateTime and if you really want to be able to access it as a string then make another property that only has a get accessor that is the tostring of the datetime in the format you want.
You could then sort by the DateTime property that you set, but use the formatted date property in whatever report you're displaying.
CodePudding user response:
I have no way to change the variables within the RegisteredRequest class. So I had to convert the strings to date time so I could use OrderBy as @lidqy said and it worked.
var orderReport = report.OrderBy(x => Convert.ToDateTime(x.requestDate).Date).ThenBy(x => Convert.ToDateTime(x.itemDate).Date);