0
我正在使用linq-to-sql的存儲庫類作爲(web)GridView的objectdatasource。 GridView必須允許在所有列上進行排序。我有一個使用this approach的工作解決方案,但我顯然更喜歡在沒有預定義的排序表達式列表的情況下執行此操作。如何實現從linq-to-sql查詢中定製返回類型的排序?
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; }
}
}