首页 > 解决方案 > 动态更改选择表达式

问题描述

我正在构建一个包含多个选项的报告,每个选项都会更改报告的输出。所以为了清理我的代码,我写了这样的查询:

var results = sgdb.AccVchItm.Where(predicate).Where(predicateForDate).GroupBy(groupBy).Select(selectBy).ToList();

查询工作正常,但我的代码开始变得丑陋,我想清理它。所以这里是丑陋的部分:

对于selectBy我有这样的表达:

Expression<Func<IGrouping<ReportComparativeGroupByDto, AccVchItm>, ReportComparativeDto>> selectBy = x =>
            new ReportComparativeDto();

为了寻找选项,我做了几个这样的 If-Else:

if (viewModel.NatureOfTheReportSimple == ReportComparativeAccountingType.PrimaryLevel)
{
    selectBy = x => new ReportComparativeDto()
    {
        Remaind = x.Sum(s => s.Debit) - x.Sum(s => s.Credit),
        RemaindDebit = x.Sum(s => s.Debit),
        RemaindCredit = x.Sum(s => s.Credit),
        CrossTabColumn1 = x.Key.Year,
        CrossTabColumn2 = x.Key.Year,
        Code = x.Key.PrimaryCode,
        Title = x.Key.PrimaryTitle,
    };
} else
if (viewModel.NatureOfTheReportSimple == ReportComparativeAccountingType.GroupLevel)
{
    selectBy = x => new ReportComparativeDto()
    {
        Remaind = x.Sum(s => s.Debit) - x.Sum(s => s.Credit),
        RemaindDebit = x.Sum(s => s.Debit),
        RemaindCredit = x.Sum(s => s.Credit),
        CrossTabColumn1 = x.Key.Year,
        CrossTabColumn2 = x.Key.Year,
        Code = x.Key.GroupCode,
        Title = x.Key.GroupTitle,
    };
} else
if (viewModel.NatureOfTheReportSimple == ReportComparativeAccountingType.SpecifiedLevel)
{
    selectBy = x => new ReportComparativeDto()
    {
        Remaind = x.Sum(s => s.Debit) - x.Sum(s => s.Credit),
        RemaindDebit = x.Sum(s => s.Debit),
        RemaindCredit = x.Sum(s => s.Credit),
        CrossTabColumn1 = x.Key.Year,
        CrossTabColumn2 = x.Key.Year,
        Code = x.Key.SpecifiedCode,
        Title = x.Key.SpecifiedTitle,
    };
}

请注意,每个 If-Else 语句中只有CodeandTitle发生变化,其余部分相同。此示例是此报告中最简单的部分,并且还有许多其他具有复杂输出的选项。

所以我的问题是我如何才能在开始部分只提到和code删除其余的字段?titleselectBy

标签: c#entity-frameworkexpression

解决方案


推荐阅读