我的问题是重复的代码:一个不太 DRY 的 switch 语句。
所以我有一个包含 12 列的表格,可以通过单击按降序或升序排序。我当前的解决方案是使用 switch 语句来检查单击了哪一列。
可排序属性:
在这个页面中,如果用户单击头部,表格就会被排序:
SortByColumn
属性采用字符串形式。 SortAscending
bool 值来自 @Html.CheckBoxFor
。
你知道这是怎么回事吗?我有 12 个可以订购的列,因此这个开关可能会变得非常冗长且难以维护。所以我的问题是,是否可以通过反射或其他方式重构它?
最佳答案
OrderBy 函数的工作原理是让您返回应排序的属性,它将针对列表中的每个项目调用。
我们可以使用反射来代替硬编码:
public ActionResult Index(AgentReportViewModel vm)
{
var b = Agent.GetAgents();
vm.Agents = vm.SortAscending
? b.OrderBy(x => GetValueByColumn(x, vm.SortByColumn))
: b.OrderByDescending(x => GetValueByColumn(x, vm.SortByColumn));
return View(vm);
}
public object GetValueByColumn<T>(T x, string columnStr)
{
// Consider caching the property info, as this is a heavy call.
var propertyInfo = x.GetType().GetProperty(columnStr);
return propertyInfo.GetValue(x, null);
}
关于C# 重构巨大的 switch 语句以使用 LINQ 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30888276/