I have this code which I am upgrading to .NET 8.
The intention is to sort and filter the resultset using the parameters. Right now it has a lot of if else and redundant code inside the blocks.
I would ideally like to refactor this code to avoid redundancy and I am thinking about using a predicate, but I am unsure on how to proceed.
Code:
var model = new PagedResourceModel();
var resources = _context.DistrictResources
.Where(t => t.ResourceType == resourceType);
var resourceCount = resources.Count();
// there are 6 similar filters
if (!string.IsNullOrEmpty(request.filter.FName))
{
resources = resources
.Where(r => r.FName.ToUpper().Contains(request.filter.FName.ToUpper()));
}
if (!string.IsNullOrEmpty(request.filter.Type))
{
// same as above using request.filter.Type
}
model.LastRow = resources.Count();
var sortField = request.sortField.ToUpper();
var sortDirection = request.sortDirection.ToUpper();
switch (sortField)
{
case "FNAME":
if (sortDirection == "ASC")
{
resources = resources.OrderBy(r => r.FName)
.Skip(request.pageNumber - 1).Take(request.pageSize);
}
else
{
resources = resources.OrderByDescending(r => r.FName)
.Skip(request.pageNumber - 1).Take(request.pageSize);
}
break;
case "TYPE":
//same as above using r.Type
break;
default:
resources = resources.OrderBy(x => x.DisplayName)
.Skip(request.pageNumber - 1).Take(request.pageSize);
break;
}
model.Rows = resources.ToList();
return model;
The request type is:
public class ResourceRequest
{
public int pageNumber { get; set; }
public int pageSize { get; set; }
public string sortField { get; set; }
public string sortDirection { get; set; }
public RequestFilter filter { get; set; }
}
public class RequestFilter
{
// many more filters here
public string? FName { get; set; }
public string? Type { get; set; }
}
What would be a good way to refactor this?
_context
used here is of type Microsoft.EntityFrameworkCore.DbContext
_context
isDbContext
or releated to any type ofORM
contexts such as Entity Framework? as there is a difference between using aLinq
withIQueryable
andIEnumerable
. \$\endgroup\$