如何创建用于动态排序的表达式

时间:2016-05-25 21:48:08

标签: c#

我正在尝试动态创建一个排序表达式,我给出要排序的列的名称,排序的方向,我知道我正在排序的对象类型,但我没有IQueryable或任何东西。

这是我提出的功能,但语法错误:

    private static Expression<Func<Opportunity, Object>> AddSortExpression(string sortOrder)
    {
        Func<Opportunity, Object> func;
        switch (sortOrder)
        {
            case "DATE_CREATED":
                func = Expression.Lambda<Func<Opportunity, Object>>().OrderBy(x => x.DATE_CREATED_UTC);
                break;
            case "DATE_CREATED_DESC":
                func = Expression.Lambda<Func<Opportunity, Object>>().OrderByDescending(x => x.DATE_CREATED_UTC);
                break;
            case "FORECAST_CLOSE_DATE":
                func = Expression.Lambda<Func<Opportunity, Object>>().OrderByDescending(x => x.FORECAST_CLOSE_DATE);
                break;
            case "RESPONSIBLE_USER":
                func = Expression.Lambda<Func<Opportunity, Object>>().OrderBy(x => x.RESPONSIBLE_USER_ID);
                break;
            case "PIPELINE_STAGE":
                func = Expression.Lambda<Func<Opportunity, Object>>().OrderBy(x => x.PIPELINE_ID);
                break;
            default:
                func = Expression.Lambda<Func<Opportunity, Object>>().OrderBy(x => x.OPPORTUNITY_NAME);
                break;
        }
        return Expression.Lambda<Func<Opportunity, Object>>(Expression.Call(func.Method));
    }

这个的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

没有理由不能将查询传递给您的方法并应用适当的orderby调用。

private static IOrderedQueryable<Opportunity> AddSortExpression(IQueryable<Opportunity> source, OpportunitySortOrder sortOrder)
{
    switch (sortOrder)
    {
    case OpportunitySortOrder.DateCreated:
        return source.OrderBy(x => x.DATE_CREATED_UTC);
    case OpportunitySortOrder.DateCreatedDesc:
        return source.OrderByDescending(x => x.DATE_CREATED_UTC);
    case OpportunitySortOrder.ForecastCloseDate:
        return source.OrderByDescending(x => x.FORECAST_CLOSE_DATE);
    case OpportunitySortOrder.ResponsibleUser:
        return source.OrderBy(x => x.RESPONSIBLE_USER_ID);
    case OpportunitySortOrder.PipelineStage:
        return source.OrderBy(x => x.PIPELINE_ID);
    case OpportunitySortOrder.Name:
    default:
        return source.OrderBy(x => x.OPPORTUNITY_NAME);
    }
}