繁体   English   中英

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

[英]C# Refactoring gigantic switch statement for ordering with LINQ

我的问题是重复代码:一个不那么干的switch语句。

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

可排序的属性:

在此处输入图片说明

在此页面上,如果用户单击头部,表格将被排序:

在此处输入图片说明

SortByColumn属性以字符串形式提供。 SortAscending布尔值来自@Html.CheckBoxFor

在此处输入图片说明

你知道这是怎么回事吗? 我有12列可以订购,因此此开关可能会变得很长且无法维护。 所以我的问题是,是否可以通过反射或其他方式重构它?

OrderBy函数的工作原理是让您返回应该对其进行排序的属性,该属性将在列表中称为foreach项。

除了对其进行硬编码,我们可以使用反射代替:

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);
}

您可以在这种情况下使用表达式树。

public static Func<Agent, object> GetOrderBySelector(string propertyName)
{
    var parameter = Expression.Parameter(typeof(Agent), "a");
    var property = Expression.Property(parameter, propertyName);
    // a => a.PropertyName is a unary expression
    var unaryExpression = Expression.Convert(property, typeof(object));
    // Create the lambda for the unary expression with the given property 
    // information and compile to return the actual delegate.
    return Expression.Lambda<Func<Agent, object>>(unaryExpression, parameter).Compile();
}

用法:

b.OrderBy(vm.SortByColumn) 

要么

b.OrderByDescending(vm.SortByColumn) 

希望这可以帮助。

尝试这个:

var SortByColumnStr = "Answer"; //Dynamic string
var propertyInfo = typeof(Agent).GetProperty(SortByColumnStr);    
List<Agent> b.OrderBy(x => propertyInfo.GetValue(x, null));

参考: https : //stackoverflow.com/a/7265394/1660178

看一下System.Linq.Dynamic(可用的NuGet包)。

然后,您可以执行以下操作:

string sortingString = string.Format("{0} {1}",vm.OrderByColumn, vm.SortAscending ? "ASC" : "DESC");
vm.Agents = Agent.GetAgents().OrderBy(sortingString).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM