0

I have a list that contains an object. The object has a string property called AppointmentTime. This is used in my view, Arguably this may be better as a DateTime property using stringFormat on the binding.

So my objects may have an AppointmentTime that looks Something like this:

Object1.AppointmentTime = "12.41"
Object2.AppointmentTime = "13.49"
Object3.AppointmentTime = ""
Object4.AppointmentTime = "9.43"

I now want to sort this list by this property, with the empty strings at the bottom of the list

So far I have tried:

ListofObjects.OrderBy(x => Convert.ToDecimal(x.AppointmentTime);

but without luck... Any ideas?

EDIT - My Solution

As someone in the comment very kindly pointed out. Using the OrderBy creates a new list and does not order the original list. Silly Microsoft, should warn you that you have not set the new list equal to anything. My Final Solution was:

diaryEntries = new ObservableCollection<DiaryEntryViewModel>(diaryEntries.OrderBy(x => x.AppointmentTime).OrderBy(x => string.IsNullOrEmpty(x.AppointmentTime)));

Although I feel the longterm solution is to change this property to a DateTime as suggested

JKennedy
  • 18,150
  • 17
  • 114
  • 198
  • I think you answered your question in the second sentence, better to use a `DateTime` (or `DateTime?`) data type :) – DavidG Jul 28 '14 at 15:02

2 Answers2

3

I would change my AppointmentTime to a DateTime and then the OrderBy would be a piece of cake:

ListofObjects = ListofObjects.OrderBy(x => x.AppointmentTime).ToList();

As for the View you refer to, you can later format the string representation of your DateTime as you want. This way you will have achieve the easiest way to order your data and then you will have the required format in your view.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

The problem is passing "" to Convert.ToDecimal: you would trigger an exception. You could work around this issue by adding an explicit check, like this:

ListofObjects.OrderBy(x => string.IsNullOrEmpty(x.AppointmentTime) ? null : (decimal?)Convert.ToDecimal(x.AppointmentTime));

However, the best approach would be using a built-in type to represent the time. For example, a nullable TimeSpan? could be used to represent the time of an appointment.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523