我有一个IEnumerable通过以下方式检索的数据库对象:
var customers = _dbcontext.Customer.Where(x => x.ClientId > 0 && x.isDeleted == null);
customers = sortCustomers(customers, sortOrder, sortDirection);
要对IEnumerable客户进行排序,我有一个称为SortCustomers()
的方法(在下面实现),该方法将sortOrder
参数映射到用于排序的属性。它还使用sortDirection
确定是使用下降还是上升方向。
我最初使用的是orderBy()
,它会上升,然后如果指定了下降的方向,则在最终结果中使用Reverse()
。
产生较长代码和重复代码的另一个选项是在每个步骤使用OrderByDescending()(请参见下面的代码)。
在这种情况下(不取消延迟加载),使用IEnumerable <>。Reverse()是否与OrderByDescending()相同?
选项1:
private IEnumerable<Customer> sortCustomers(IEnumerable<Customer> unsortedCustomers, string sortOrder, string sortDirection)
{
if (sortOrder == MODEL.VMSortDescriptors.CustomerVMSortDescriptor.CompanyName.ToString())
{
unsortedCustomers = unsortedCustomers.OrderBy(c => c.CompanyName);
}
else if (sortOrder == MODEL.VMSortDescriptors.CustomerVMSortDescriptor.ContactPerson.ToString())
{
unsortedCustomers = unsortedCustomers.OrderBy(c => c.ContactPerson);
}
else if (sortOrder == MODEL.VMSortDescriptors.CustomerVMSortDescriptor.EmailId.ToString())
{
unsortedCustomers = unsortedCustomers.OrderBy(c => c.EmailId);
}
//many more sort properties
//Asc or Desc
if (sortDirection == VMSortDescriptors.SortDirection.Descending.ToString())
unsortedCustomers = unsortedCustomers.Reverse();
return unsortedCustomers;
}
选项2:
private IEnumerable<Customer> sortCustomers(IEnumerable<Customer> unsortedCustomers, string sortOrder, string sortDirection)
{
bool isAscendingOrder = (sortDirection == VMSortDescriptors.SortDirection.Ascending.ToString());
if (sortOrder == MODEL.VMSortDescriptors.CustomerVMSortDescriptor.CompanyName.ToString())
{
if (isAscendingOrder)
unsortedCustomers = unsortedCustomers.OrderBy(c => c.CompanyName);
else
unsortedCustomers = unsortedCustomers.OrderByDescending(c => c.CompanyName);
}
else if (sortOrder == MODEL.VMSortDescriptors.CustomerVMSortDescriptor.ContactPerson.ToString())
{
if (isAscendingOrder)
unsortedCustomers = unsortedCustomers.OrderBy(c => c.ContactPerson);
else
unsortedCustomers = unsortedCustomers.OrderByDescending(c => c.ContactPerson);
}
else if (sortOrder == MODEL.VMSortDescriptors.CustomerVMSortDescriptor.EmailId.ToString())
{
if (isAscendingOrder)
unsortedCustomers = unsortedCustomers.OrderBy(c => c.EmailId);
else
unsortedCustomers = unsortedCustomers.OrderByDescending(c => c.EmailId);
}
//many more sort properties
return unsortedCustomers;
}
更新
关于将sortOrder参数映射到属性,是的,我可以使用反射或某些方法来获取IEnumerable中各项的属性值。最初,我是使用通用排序功能完成的。但是,匿名元组结果使事情变得复杂。所以我决定简单而直接。