I have the List
method that takes sorting parameter to sort results. The sorting parameter value is the same as the column name.
public ActionResult List(string sorting = "Name", string sortingMethod = "ASC")
{
var productList = productRepository.Get();
if(!String.IsNullOrEmpty(Sorting){
if(String.IsNullOrEmpty(SortingMethod) ||SortingMethod == "ASC"){
switch(sorting){
case "Name" :
productList = productList.OrderBy(x => x.Name); break;
case "Price" :
productList = productList.OrderBy(x => x.Price); break;
case "Category" :
productList = productList.OrderBy(x => x.Price); break;
//...
}
}else{
switch(sorting){
case "Name" :
productList = productList.OrderByDescending(x => x.Name); break;
case "Price" :
productList = productList.OrderByDescending(x => x.Price); break;
case "Category" :
productList = productList.OrderByDescending(x => x.Price); break;
//...
}
}
}
return View(productList.ToList());
}
But I believe there is a better way to make code shorter.
public ActionResult List(string sorting = "Name", string sortingMethod = "ASC")
{
var productList = productRepository.Get();
if(!String.IsNullOrEmpty(Sorting){
if(String.IsNullOrEmpty(SortingMethod) ||SortingMethod == "ASC"){
productList = productList.OrderBy(); // <== ???
}else{
productList = productList.OrderByDescending(); // <== ???
}
}
return View(productList.ToList());
}