views:

39

answers:

1

I am using a repository class with linq-to-sql as the objectdatasource for a (web) GridView. The GridView has to allow sorting on all columns. I have a working solution using this approach but I would obviously prefer to do this without a predefined list of sort expressions.

public class TrailerMovementRepository
{
    private TrailerMovementDataContext db = new TrailerMovementDataContext();

    public IOrderedEnumerable<TrailerMovementHistory> GetTrailerMovementHistoryByDepotAndDate(string depot, DateTime searchDate, string sortExpression)
    {
        var unorderedQuery = (from tm in db.TrailerMovements
               where tm.Depot == depot && tm.Date_In == searchDate && tm.Time_Out != null               
               select new TrailerMovementHistory
               {
                   Depot = tm.Depot,
                   TrailerNumber = tm.Trailer,
                   TimeIn = tm.Time_In,
                   TimeOut = tm.Time_Out,
                   VOR = tm.VOR.Value,
                   Contents = tm.Contents,
                   Supplier = tm.Supplier,
                   TurnaroundTime = FormatDuration(tm.Time_Out - tm.Time_In),
                   VORTime = FormatDuration(tm.VOnR_Date - tm.VOffR_Date),
                   LoadedTime = tm.LoadedTime,
                   Destination = tm.Destination
               }).ToList<TrailerMovementHistory>();

        //need to find a way to dynamically do this from the passed in expression
        IOrderedEnumerable<TrailerMovementHistory> orderedQuery = unorderedQuery.OrderBy(t => t.TrailerNumber);

        switch (sortExpression)
        {
            case "TrailerNumber DESC":
                orderedQuery = unorderedQuery.OrderByDescending(t => t.TrailerNumber);
                break;
            case "TimeIn":
                orderedQuery = unorderedQuery.OrderBy(t => t.TimeIn);
                break;
            case "TimeIn DESC":
                orderedQuery = unorderedQuery.OrderByDescending(t => t.TimeIn);
                break;

            ...etc...

            default:
                break;
        }
        return orderedQuery;
    }

    public class TrailerMovementHistory
    {
        public TrailerMovementHistory()
        { }
        public String Depot { get; set; }
        public String TrailerNumber { get; set; }
        public DateTime? TimeIn { get; set; }
        public DateTime? TimeOut { get; set; }
        public Boolean VOR { get; set; }
        public String Contents { get; set; }
        public String Supplier { get; set; }
        public String TurnaroundTime { get; set; }
        public String VORTime { get; set; }
        public DateTime? LoadedTime { get; set; }
        public String Destination { get; set; }

    }
}
A: 

You might want to check out: SO

Joshua Cauble