I have these lines of code which adds item to a dropdown list and sorts them by hearing date and then by time. I would like to take it a step further and sort by the ‘type’ or description of the item in alphabetical order.
this is my code in my Controller:
public void AddHearingsToViewModel(CourtActivityViewModel viewModel, IQueryable<Hearing> hearings)
{
if (viewModel.HearingEntryId == Guid.Empty)
viewModel.HearingEntryId = hearings.OrderByDescending(h => h.HearingDate).ThenByDescending(d=>d.HearingDate).FirstOrDefault().HearingEntryId;
viewModel.Hearings = hearings.ToSelectList("HearingEntryId", "CourtActivitySelection", viewModel.HearingEntryId.ToString());
}
My ..Domain.Entities.Hearing
public partial class Hearing
{
public string CourtActivitySelection
{
get { return string.Format(@"{0:d} - {0:t} - {1} ", HearingDate, HearingType.Description); }
}
public override string ToString()
{
return string.Format(@"{1} on {0:d} @ {0:t}", HearingDate, HearingType.Description);
}
}
public partial class HearingEntry
{
public override string ToString()
{
return string.Format(@"{1} on {0:d} @ {0:t}", HearingDate, HearingType.Description);
}
}
I tried:
viewModel.HearingEntryId = hearings.OrderByDescending(h => h.HearingDate).ThenByDescending(d=>d.HearingDate).OrderBy(t=>t.HearingType).FirstOrDefault().HearingEntryId;
The exact error is :
Cannot order by type ‘Kids.Domain.Entities.HearingType’.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Cannot order by type ‘Kids.Domain.Entities.HearingType’.
And the line in red is the line i added the .ThenBy(t=>t.HearingType)
Looks like your
HearingTypeis a class that does not implement IComparable. Either implement this interface on the Type that HearingType isor change your code to
The only problem you may run into (since I don’t know how your classes are populated, is that
HearingTypecould benull.