I'm trying to make a GET request that sorts the results by a sortBy
criteria.
Unfortunately the SortBy
method doesn't return a sorted list.
Here is the GET request.
[HttpGet]
public IHttpActionResult GetComupters(int? Id=null, string ModelName=null, string ManufacturerCompanyName=null,
string CPU=null, int? RAM=null, int? Memory=null, int? ScreenSize=null,
int? Price=null, int? MinPrice=null, int? MaxPrice=null, string sortBy=null)
{
var searchModel = new ComputerSearchModel()
{
Id = Id,
ModelName = ModelName,
ManufacturerCompanyName = ManufacturerCompanyName,
CPU = CPU,
RAM = RAM,
Memory = Memory,
ScreenSize = ScreenSize,
Price = Price,
MaxPrice = MaxPrice,
MinPrice = MinPrice
};
var computers = ComputerFilter(searchModel);
ComputerSort(computers.ToList(),sortBy);
return Ok(computers);
}
Here is the sorting function:
private List<Computer> ComputerSort(List<Computer> computers, string sortBy = null)
{
if (string.IsNullOrEmpty(sortBy))
{
return computers;
}
switch (sortBy.ToLower())
{
case "price":
computers = computers.OrderBy(computer => computer.Price).ToList();
break;
}
return computers;
}
Here is the Computer
model class - just in case:
public int Id { get; set; }
public string ModelName { get; set; }
public string ManufacturerCompanyName { get; set; }
public string CPU { get; set; }
public int RAM { get; set; }
public int Memory { get; set; }
public int ScreenSize { get; set; }
public int Price { get; set; }
Could someone please take a look of why the sortBy method doesn't work?
CodePudding user response:
Because you don't do anything with the return value:
ComputerSort(computers.ToList(),sortBy);
Should be:
computers = ComputerSort(computers.ToList(),sortBy);