Lets say I have an entity like:
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public DateTime ReleaseDate { get; set; }
public int NumCreated { get; set; }
}
We are using a simple MVP architecture for our site with a View Layer (ASP.NET website, Presenter Layer (C# Class Library), Logic Layer (C# Class Library), Data Layer (C# Class Library).
Lets say I have a view that displays a list of cars with sortable column headers. What I've been doing in the past is doing all my sorting in my logic layer, and the view passing an enum for whatever column the list of entities needs to be sorted by.
This is a pain though because I need to maintain an enum for every entity I have and an entry in that enum for every property in the entity.
So, for example, we would be doing something like:
CarLogic.cs
public IEnumerable<Car> GetCarsByYear(string year, SortColumn sortColumn, SortOrder sortOrder)
{
List<Car> cars = _carRepository.GetCarsByYear(year);
switch (sortColumn)
{
case SortColumn.Make:
cars.Sort((car1, car2) =>
sortOrder == SortOrder.Ascending
? car1.Make.CompareTo(car2.Make) :
car2.Make.CompareTo(car1.Make);
break;
case SortColumn.Model:
cars.Sort((car1, car2) =>
sortOrder == SortOrder.Ascending
? car1.Model.CompareTo(car2.Model) :
car2.Model.CompareTo(car1.Model);
break;
case SortColumn.ReleaseDate:
cars.Sort((car1, car2) =>
sortOrder == SortOrder.Ascending
? car1.ReleaseDate.CompareTo(car2.ReleaseDate) :
car2.ReleaseDate.CompareTo(car1.ReleaseDate);
break;
case SortColumn.NumCreated:
cars.Sort((car1, car2) =>
sortOrder == SortOrder.Ascending
? car1.NumCreated.CompareTo(car2.NumCreated) :
car2.NumCreated.CompareTo(car1.NumCreated);
break;
// ...
}
return cars;
}
This is how I have been doing it. However, it is a very manual process and if an entity has quite a few properties it can be annoying.
What would be a better way to handle this? Is it possible to allow my collection of entities to be sortable on properties without having to do it all manually per-property like this?