Sorting optimization for date

I have been sorting a collection like this. i was wondering whether it can be optimized or not. please have a look:

//ordering elements i.e latest ToDate will be on top and if ToDate are same then latest FromDate will be in top
var posistions = (someModel.Positions.OrderByDescending(x => x.ToDate)
    .ThenByDescending(x => x.FromDate).Where(x => !x.ToDate.HasValue).ToArray())
    .Concat(someModel.Positions.OrderByDescending(x => x.FromDate)
    .ThenByDescending(x => x.ToDate).Where(x => x.ToDate.HasValue).ToArray());

someModel.Positions = posistions.ToArray();

Upvotes: 0

Views: 47

Answers (2)

See fiddle: https://dotnetfiddle.net/nNbT5D

a small adjustment to the accepted answer:

.OrderBy(x => x.ToDate ?? DateTime.MinValue)
.ThenByDescending(x => x.FromDate);

this code is enough to replicate the result.

see the result using this sorting criteria

From: 8/4/2018 7:35:00 AM ========= ToDate: 
From: 7/25/2018 7:35:00 AM ========= ToDate: 
From: 6/25/2018 7:35:00 AM ========= ToDate: 8/9/2018 7:35:00 AM
From: 7/5/2018 7:35:00 AM ========= ToDate: 8/10/2018 7:35:00 AM
From: 8/11/2018 7:35:00 AM ========= ToDate: 8/11/2018 7:35:00 AM

 result using question's sorting criteria below
From: 8/4/2018 7:35:00 AM ========= ToDate: 
From: 7/25/2018 7:35:00 AM ========= ToDate: 
From: 8/11/2018 7:35:00 AM ========= ToDate: 8/11/2018 7:35:00 AM
From: 7/5/2018 7:35:00 AM ========= ToDate: 8/10/2018 7:35:00 AM
From: 6/25/2018 7:35:00 AM ========= ToDate: 8/9/2018 7:35:00 AM

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81523

You could probably just do something like this. I am not sure what polarity you need from the ordering however its easily changed

var positions = model.Positions
                     .OrderByDescending(x => x.ToDate.HasValue)
                     .ThenByDescending(x => x.ToDate)
                     .ThenByDescending(x => x.FromDate);

foreach (var pos in positions)
   Console.WriteLine(pos.ToDate+" : " + pos.FromDate);    

Output

8/8/2018 5:34:49 AM : 8/8/2018 5:34:49 AM
8/7/2018 5:34:49 AM : 7/2/2018 5:34:49 AM
8/6/2018 5:34:49 AM : 6/22/2018 5:34:49 AM
null : 8/1/2018 5:34:49 AM
null : 7/22/2018 5:34:49 AM

Full Demo Here

Upvotes: 2

Related Questions