如何改善此排序代码? [英] How can I improve this sorting code?
本文介绍了如何改善此排序代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在检查sort参数并构建一堆if
语句:
I'm checking the sort parameter and building a bunch of if
statements:
if (sortDirection == "ASC")
{
if (sortBy == "Id")
return customerList.OrderBy(x => x.Id).Skip(startIndex).Take(pageSize).ToList();
if (sortBy == "FirstName")
return customerList.OrderBy(x => x.FirstName).Skip(startIndex).Take(pageSize).ToList();
if (sortBy == "City")
return customerList.OrderBy(x => x.City).Skip(startIndex).Take(pageSize).ToList();
}
else
{
if (sortBy == "Id")
return customerList.OrderByDescending(x => x.Id).Skip(startIndex).Take(pageSize).ToList();
if (sortBy == "FirstName")
return customerList.OrderByDescending(x => x.FirstName).Skip(startIndex).Take(pageSize).ToList();
if (sortBy == "City")
return customerList.OrderByDescending(x => x.City).Skip(startIndex).Take(pageSize).ToList();
}
我该如何做得更好?
推荐答案
将您的订购与其余查询分开-无需在代码库中重复的每个查询的相同部分(请保留 DRY ):
Separate your ordering and the rest of the query - the parts that are the same for each query you don't have to duplicate in your codebase (keep it DRY):
var query = customerList;
if (sortDirection == "ASC")
{
if (sortBy == "Id")
query = query.OrderBy(x => x.Id);
///and so on
}
query = query.Skip(startIndex).Take(pageSize).ToList();
这篇关于如何改善此排序代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文