Home > Software engineering >  sort date in descending order and for same dates sort time also in descending order
sort date in descending order and for same dates sort time also in descending order

Time:06-23

for the sample input:

11/18/2021 10:29:39 PM
11/17/2021 8:26:39 PM
11/18/2021 8:44:39 PM
11/19/2021 9:04:39 PM
11/19/2021 8:54:39 PM

firstly I need to sort dates in descending order and for same dates I need to sort time also in descending order.

for the same I have a query in this form

List<some> orderedData = data.OrderByDescending(c => c.ModifiedOn.Date).ThenBy(c => c.ModifiedOn.TimeOfDay).ToList(); 

the dates are getting arranged in descending order but facing issue with the arranging time also in descending order. please help me on this

expected output:
11/19/2021 9:04:39 PM
11/19/2021 8:54:39 PM
11/18/2021 10:29:39 PM
11/18/2021 6:44:39 PM
11/17/2021 11:26:39 PM

CodePudding user response:

Since you're essentially sorting the whole Date Time in Descending order, you should just do the Order By Descending on ModifiedOn as follows:

List<some> orderedData = data.OrderByDescending(c => c.ModifiedOn).ToList(); 

CodePudding user response:

The OrderByDescending() method sorts the collection in Descendingorder based on Date and ThenByDescending() method after OrderBy to sort the collection on TimeOfDay in Descending order Linq will first sort the collection based on primary field which is specified by OrderByDescending method and then sort the resulted collection in Descending order again based on secondary field specified by ThenByDescending method for Example

List<DateTime> holidays = new List<DateTime>();
    DateTime today = DateTime.Today;
    holidays.Add(today.AddHours(2));
    holidays.Add(today.AddDays(5).AddHours(6));
    holidays.Add(today.AddDays(5).AddHours(8));
    holidays.Add(today.AddDays(5).AddHours(4));
    holidays.Add(today.AddDays(3).AddHours(3));
    var orderedDateList =  holidays.OrderByDescending(x => x).ThenByDescending(y => y.TimeOfDay).ToList();
    foreach(var i in orderedDateList){
    Console.WriteLine(i);
        
    }

result :

06/28/2022 08:00:00

06/28/2022 06:00:00

06/28/2022 04:00:00

06/26/2022 03:00:00

06/23/2022 02:00:00

  • Related