简体   繁体   中英

Sort list by date closest to now but not old dates

I have a list with dates that I would like to sort according to:

  • Dates that is today should be sorted in the top
  • Dates that is in the future should be sorted by closest date today (example today = 8th and we have the dates 18, 9, 11 should be sorted => 9, 11, 18)
  • Dates older then today's date should be listed in the bottom of the list descending.

What is the best way to do this ?:

  • Is it to create a future list,

  • old list and present list and then concat and sort them?

  • Or can i achieve this in a better way?

To to make this even clearer this is how the sorted list should look like:

today => tomorrow => day after tomorrow => days in future.... => yesterday => older then yesterday

在此处输入图片说明

var dates = new List<DateTime>()
{
    DateTime.Today,
    DateTime.Today.AddDays(1),
    DateTime.Today.AddDays(-2),
    DateTime.Today.AddDays(5),
    DateTime.Today.AddDays(-5)
};

Dates that is today should be sorted in the top

DateTime today = dates.Where(x => x == DateTime.Today).First();

Dates that is in the future should be sorted by closest date today (example today = 8th and we have the dates 18, 9, 11 should be sorted => 9, 11, 18)

List<DateTime> futureDates = dates.Where(x => x > today).ToList();
futureDates.Sort();

Dates older then today's date should be listed in the bottom of the list descending.

List<DateTime> oldDates = dates.Where(x => x < today).OrderByDescending(x => x).ToList();

And this is the final aggregated result:

var final = new List<DateTime>();
final.Add(today);
final.AddRange(futureDates);
final.AddRange(oldDates);

<== Fiddle ==>

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