我有一种方法可以在我的 c# 后端按列排序。我正在从前端传递 SortBy 和 SortOrder 参数。我当前的代码运行良好,但我想减少行数并编写通用代码。
这是我当前的代码。
public async Task<IEnumerable<Logs>> SearchLogs (SearchParameters parameters){
Sort<Logs> sort = GetSort(parameters);
result = await _mongoDb.GetCollection<Logs>(Logs)
.Sort(sort)
.ToListAsync<Logs>();
return _mapper.Map<IEnumerable<Logs>>(result);
}
private static Sort<Logs> GetSort(SearchParameters parameters){
var sort = Builders<Logs>.Sort.Descending(x => x.Date);
if(parameters.SortBy == "name" && parameters.SortOrder == "asc") {sort = Builders<Logs>.Sort.Ascending(x=> x.Name);}
else if(parameters.SortBy == "name" && parameters.SortOrder == "desc") {sort = Builders<Logs>.Sort.Descending(x=> x.Name);}
else if(parameters.SortBy == "age" && parameters.SortOrder == "asc") {sort = Builders<Logs>.Sort.Ascending(x=> x.Age);}
else if(parameters.SortBy == "age" && parameters.SortOrder == "desc") {sort = Builders<Logs>.Sort.Descending(x=> x.Age);}
else if(parameters.SortBy == "address" && parameters.SortOrder == "asc") {sort = Builders<Logs>.Sort.Ascending(x=> x.Address);}
else if(parameters.SortBy == "address" && parameters.SortOrder == "desc") {sort = Builders<Logs>.Sort.Descending(x=> x.Address);}
return sort;
}
如何通过修改 else if 条件来减少代码行数?
谢谢!