C# 重构巨大的 switch 语句以使用 LINQ 进行排序

标签 c# asp.net-mvc linq dry

我的问题是重复的代码:一个不太 DRY 的 switch 语句。

所以我有一个包含 12 列的表格,可以通过单击按降序或升序排序。我当前的解决方案是使用 switch 语句来检查单击了哪一列。

可排序属性:

enter image description here

在这个页面中,如果用户单击头部,表格就会被排序:

enter image description here

SortByColumn 属性采用字符串形式。 SortAscending bool 值来自 @Html.CheckBoxFor

enter image description here

你知道这是怎么回事吗?我有 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/

相关文章:

c# - ASP.NET MVC5,两个 Controller ,在不同的文件夹中具有相同的名称

asp.net-mvc - ASP.Net MVC 3 显示模板和编辑器模板自定义位置,如何?

asp.net-mvc - 在 Azure 网站上启用 32 位应用程序

asp.net-mvc - 从mvc中的FormCollection值中获取Fileupload值

c# - 如何有效地比较列表?

c# - 从LINQ查询结果中检索ID

c# - 使用属性公开类似数组的数据结构

c# - 如何使用异步来提高 WinForms 性能?

c# - 应该如何管理在函数范围内声明的定时器的清理?

c# - 如何使用 LINQ .ToUpper() 数组的每个元素?