c# - 动态更改选择表达式
问题描述
我正在构建一个包含多个选项的报告,每个选项都会更改报告的输出。所以为了清理我的代码,我写了这样的查询:
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 语句中只有Code
andTitle
发生变化,其余部分相同。此示例是此报告中最简单的部分,并且还有许多其他具有复杂输出的选项。
所以我的问题是我如何才能在开始部分只提到和code
删除其余的字段?title
selectBy
解决方案
推荐阅读
- php - 在 CodeIgniter 的控制器中下载“.CSV”格式的文件时我在哪里做错了?
- amazon-web-services - AWS API - 如何通过子网 ID 获取主路由表 ID?Association.subnet-id 过滤器不起作用
- c# - 如何在从 DevOps 提取的解决方案中使用 DevOps nuget 包
- verilog - 从循环变量创建一个 int 参数
- c# - 如何为目标类建模以在 .NET5 中接收 JSON html 响应
- vb.net - VB.net查找除0以外的最小数字
- pandas - 使用子 ID 计算列中的唯一值
- python - 如何增加 cv2.findContours 返回的轮廓点数以计算 3D 图像上的主轴?
- c++ - 递归函数在没有特定停止规则时的时间复杂度
- python - 调整树状图的高度